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 |
||
12 | class Product extends Combinatorics implements \Iterator, \Countable |
||
13 | { |
||
14 | /** |
||
15 | * The key. |
||
16 | * |
||
17 | * @var int |
||
18 | */ |
||
19 | protected $key; |
||
20 | |||
21 | /** |
||
22 | * The iterators. |
||
23 | * |
||
24 | * @var \Iterator[] |
||
25 | */ |
||
26 | protected $iterators = []; |
||
27 | |||
28 | /** |
||
29 | * Product constructor. |
||
30 | * |
||
31 | * @param array $datasetArray |
||
32 | * The array of dataset. |
||
33 | */ |
||
34 | 4 | public function __construct(array $datasetArray) |
|
35 | { |
||
36 | 4 | parent::__construct($datasetArray); |
|
37 | |||
38 | 4 | foreach ($datasetArray as $dataset) { |
|
39 | 4 | $this->iterators[] = new \ArrayIterator($dataset); |
|
40 | 4 | } |
|
41 | |||
42 | 4 | $this->key = 0; |
|
43 | 4 | } |
|
44 | |||
45 | /** |
||
46 | * {@inheritdoc} |
||
47 | */ |
||
48 | 4 | public function current() |
|
49 | { |
||
50 | 4 | $tuple = []; |
|
51 | |||
52 | 4 | foreach ($this->iterators as $iterator) { |
|
53 | 4 | $tuple[] = $iterator->current(); |
|
54 | 4 | } |
|
55 | |||
56 | 4 | return $tuple; |
|
57 | } |
||
58 | |||
59 | /** |
||
60 | * {@inheritdoc} |
||
61 | */ |
||
62 | 4 | public function next() |
|
|
|||
63 | { |
||
64 | 4 | foreach (array_reverse($this->iterators) as $key => $iterator) { |
|
65 | 4 | $iterator->next(); |
|
66 | 4 | if ($iterator->valid()) { |
|
67 | 4 | $count_iterators = count($this->iterators); |
|
68 | 4 | foreach ($this->iterators as $key2 => $iterator2) { |
|
69 | 4 | if ($key >= $count_iterators - $key2) { |
|
70 | 4 | $iterator2->rewind(); |
|
71 | 4 | } |
|
72 | 4 | } |
|
73 | |||
74 | 4 | break; |
|
75 | } |
||
76 | 4 | } |
|
77 | |||
78 | 4 | $this->key++; |
|
79 | 4 | } |
|
80 | |||
81 | /** |
||
82 | * {@inheritdoc} |
||
83 | */ |
||
84 | public function key() |
||
88 | |||
89 | /** |
||
90 | * {@inheritdoc} |
||
91 | */ |
||
92 | 4 | public function valid() |
|
104 | |||
105 | /** |
||
106 | * {@inheritdoc} |
||
107 | */ |
||
108 | 4 | public function rewind() |
|
116 | |||
117 | /** |
||
118 | * {@inheritdoc} |
||
119 | */ |
||
120 | 4 | public function count() |
|
130 | |||
131 | /** |
||
132 | * Convert the iterator into an array. |
||
133 | * |
||
134 | * @return array |
||
135 | * The elements. |
||
136 | */ |
||
137 | 4 | View Code Duplication | public function toArray() |
147 | } |
||
148 |
This check marks variable names that have not been written in camelCase.
In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes
databaseConnectionString
.