6. Ejercicio de aplicación - TAXES con objetos (impots_03)
Volvemos al ejercicio estudiado anteriormente (secciones 4.2 y 4.3) para resolverlo utilizando código PHP que utiliza una clase.
1. <?php
2.
3. // definition of a Taxes class
4. class Taxes {
5.
6. // attributes: the 3 data arrays
7. private $limits;
8. private $coeffR;
9. private $coeffN;
10.
11. // constructor
12.
13. public function __construct($TAXES) {
14. // $IMPOTS: the name of the file containing the data for the $limites, $coeffR, and $coeffN tables
15. // Does the $IMPOTS file exist?
16. if (!file_exists($IMPOTS)) {
17. throw new Exception("The $IMPOTS file does not exist");
18. }//if
19. // read the file in blocks
20. $tables = file($IMPOTS);
21. if (!$tables) {
22. throw new Exception("Error while processing the $IMPOTS file");
23. }//if
24. // Create the 3 tables - assuming the rows are syntactically correct
25. $u = new Utilities(); // to provide utility functions
26. $this->limits = explode(":", $u->cutNewLineChar($tables[0]));
27. $this->coeffR = explode(":", $u->cutNewLineChar($tables[1]));
28. $this->coeffN = explode(":", $u->cutNewLineChar($tables[2]));
29. }
30.
31. // --------------------------------------------------------------------------
32. public function calculate($married, $children, $salary) {
33. // $marié: yes, no
34. // $children: number of children
35. // $salary: annual salary
36.
37. // number of shares
38. $married = strtolower($married);
39. if ($married == "yes")
40. $nbParts = $children / 2 + 2;
41. else
42. $nbParts = $children / 2 + 1;
43. // add 1/2 portion if there are at least 3 children
44. if ($children >= 3)
45. $nbParts+=0.5;
46. // taxable income
47. $taxableIncome = 0.72 * $salary;
48. // family quotient
49. $quotient = $taxableIncome / $numberOfChildren;
50. // is placed at the end of the limits array to stop the following loop
51. $this->limits[count($this->limits) - 1] = $quota;
52. // tax calculation
53. $i = 0;
54. while ($quotient > $this->limits[$i])
55. $i++;
56. // Since we placed $quotient at the end of the $limites array, the previous loop
57. // cannot go beyond the $limits array
58. // now we can calculate the tax
59. return floor($taxableIncome * $this->coeffR[$i] - $numberOfShares * $this->coeffN[$i]);
60. }
61.
62. }
63.
64. // a utility class
65. class Utilities {
66.
67. public function cutNewLineChar($line) {
68. // remove the end-of-line character from $line if it exists
69. $L = strlen($line); // line length
70. while (substr($line, $L - 1, 1) == "\n" or substr($line, $L - 1, 1) == "\r") {
71. $line = substr($line, 0, $L - 1);
72. $L--;
73. }//while
74. // end
75. return($line);
76. }
77.
78. }
79.
80. // test -----------------------------------------------------
81. // definition of constants
82. $DATA = "data.txt";
83. $RESULTS = "results.txt";
84. $TAXES = "taxes.txt";
85. // The data needed to calculate the tax has been placed in the TAXES file
86. // with one line per table in the form
87. // "val1":"val2":"val3",...
88. // we create a Taxes object
89. try {
90. $I = new Taxes($TAXES);
91. } catch (Exception $e) {
92. print $e->getMessage();
93. exit;
94. }
95. // create a utilities object
96. $u = new Utilities();
97.
98. // read user data
99. $data = fopen($DATA, "r");
100. if (!$data) {
101. print "Unable to open the data file [$DATA] for reading\n";
102. exit;
103. }
104.
105. // Open the results file
106. $results = fopen($RESULTS, "w");
107. if (!$results) {
108. print "Unable to create the results file [$RESULTS]\n";
109. exit;
110. }
111.
112. // process the current line of the data file
113. while ($line = fgets($data, 100)) {
114. // remove any end-of-line characters
115. $line = $u->cutNewLineChar($line);
116. // We retrieve the three fields married, children, and salary that make up $line
117. list($married, $children, $salary) = explode(",", $line);
118. // calculate the tax
119. $tax = $I->calculate($married, $children, $salary);
120. // print the result
121. fputs($results, "$married:$children:$salary:$tax\n");
122. // next data
123. }// while
124. // close the files
125. fclose($data);
126. fclose($results);
127.
128. // end
129. print "Done\n";
130. exit;
131. ?>
El archivo [taxes.txt]:
12620:13190:15640:24740:31810:39970:48360:55790:92970:127860:151250:172040:195000:0
0:0.05:0.1:0.15:0.2:0.25:0.3:0.35:0.4:0.45:0.5:0.55:0.6:0.65
0:631:1290.5:2072.5:3309.5:4900:6898.5:9316.5:12106:16754.5:23147.5:30710:39312:49062
El archivo [data.txt]
Resultados: los ya obtenidos en las versiones con tablas y ficheros.
El archivo [results.txt]
yes:2:200000:22504
no:2:200000:33388
yes:3:200000:16400
no:3:200000:22504
yes:5:50000:0
no:0:3000000:1354938
Comentarios
- Línea 4: el Impuestos clase. Encierra datos y métodos para calcular impuestos:
- datos: líneas 7-9 - estas son las tres matrices de datos utilizadas para calcular el impuesto. Estas tres matrices son inicializadas por el constructor en la línea 13 desde un archivo de texto.
- métodos: línea 32 - el `calcula calcula el impuesto.
- Líneas 17, 22: Cuando el constructor no puede crear el objeto Impuestos lanza una excepción.
- línea 25: el Servicios se definió para encapsular la clase cutNewLineChar función.
- Líneas 26-28: Inicialización de los tres campos privados del módulo Impuestos clase
- Línea 32: El
*calcula* método delImpuestos calcula el impuesto de un contribuyente. - líneas 65-78: el Servicios clase
- líneas 89-94: creación de una Impuestos con manejo de excepciones. Esta creación utilizará el archivo de texto $IMPOTS para rellenar los tres campos privados del objeto Impuestos objeto.
- Línea 96: Creación de una Servicios para acceder al objeto cutNewLineChar función.