Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
26 | class ConvertedResultIterator extends ResultIterator |
||
27 | { |
||
28 | protected $types = []; |
||
29 | protected $session; |
||
30 | protected $converters = []; |
||
31 | |||
32 | /** |
||
33 | * @param ResultHandler $result |
||
34 | * @param BaseSession $session |
||
35 | */ |
||
36 | public function __construct(ResultHandler $result, BaseSession $session) |
||
37 | { |
||
38 | parent::__construct($result); |
||
39 | $this->session = $session; |
||
40 | $this->initTypes(); |
||
41 | } |
||
42 | |||
43 | /** |
||
44 | * get |
||
45 | * |
||
46 | * Return a particular result. An array with converted values is returned. |
||
47 | * pg_fetch_array is muted because it produces untrappable warnings on |
||
48 | * errors. |
||
49 | * |
||
50 | * @param integer $index |
||
51 | * @return array |
||
52 | */ |
||
53 | public function get($index) |
||
54 | { |
||
55 | return $this->parseRow(parent::get($index)); |
||
56 | } |
||
57 | |||
58 | /** |
||
59 | * initTypes |
||
60 | * |
||
61 | * Get the result types from the result handler. |
||
62 | * |
||
63 | * @access protected |
||
64 | * @return ResultIterator $this |
||
65 | */ |
||
66 | protected function initTypes() |
||
67 | { |
||
68 | foreach ($this->result->getFieldNames() as $index => $name) { |
||
69 | $this->types[$index] = $this->result->getFieldType($name); |
||
70 | } |
||
71 | |||
72 | return $this; |
||
73 | } |
||
74 | |||
75 | /** |
||
76 | * parseRow |
||
77 | * |
||
78 | * Convert values from Pg. |
||
79 | * |
||
80 | * @access protected |
||
81 | * @param array $values |
||
82 | * @return mixed |
||
83 | */ |
||
84 | protected function parseRow(array $values) |
||
85 | { |
||
86 | $output_values = []; |
||
87 | |||
88 | foreach ($values as $name => $value) { |
||
89 | $output_values[$name] = |
||
90 | $this->convertField($name, $value) ; |
||
91 | } |
||
92 | |||
93 | return $output_values; |
||
94 | } |
||
95 | |||
96 | /** |
||
97 | * convertField |
||
98 | * |
||
99 | * Return converted value for a result field. |
||
100 | * |
||
101 | * @access protected |
||
102 | * @param string $name |
||
103 | * @param string $value |
||
104 | * @return mixed |
||
105 | */ |
||
106 | protected function convertField($name, $value) |
||
126 | |||
127 | /** |
||
128 | * slice |
||
129 | * |
||
130 | * see @ResultIterator |
||
131 | */ |
||
132 | public function slice($name) |
||
141 | } |
||
142 |