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 = array(); |
||
27 | |||
28 | /** |
||
29 | * Product constructor. |
||
30 | * |
||
31 | * @param array $datasetArray |
||
32 | * The array of dataset. |
||
33 | */ |
||
34 | 4 | public function __construct(array $datasetArray) { |
|
35 | 4 | parent::__construct($datasetArray); |
|
36 | |||
37 | 4 | foreach ($datasetArray as $dataset) { |
|
38 | 4 | $this->iterators[] = new \ArrayIterator($dataset); |
|
39 | } |
||
40 | |||
41 | 4 | $this->key = 0; |
|
42 | 4 | } |
|
43 | |||
44 | /** |
||
45 | * {@inheritdoc} |
||
46 | */ |
||
47 | 4 | public function current() { |
|
48 | 4 | $tuple = array(); |
|
49 | |||
50 | 4 | foreach ($this->iterators as $iterator) { |
|
51 | 4 | $tuple[] = $iterator->current(); |
|
52 | } |
||
53 | |||
54 | 4 | return $tuple; |
|
55 | } |
||
56 | |||
57 | /** |
||
58 | * {@inheritdoc} |
||
59 | */ |
||
60 | 4 | public function next() { |
|
61 | 4 | $reverseIterators = array_reverse($this->iterators); |
|
62 | |||
63 | 4 | foreach ($reverseIterators as $key => $iterator) { |
|
64 | 4 | $iterator->next(); |
|
65 | 4 | if ($iterator->valid()) { |
|
66 | 4 | foreach ($this->iterators as $key2 => $iterator2) { |
|
67 | 4 | if ($key >= count($this->iterators) - $key2) { |
|
68 | 4 | $iterator2->rewind(); |
|
69 | } |
||
70 | } |
||
71 | 4 | break; |
|
72 | } |
||
73 | } |
||
74 | |||
75 | 4 | $this->key++; |
|
76 | 4 | } |
|
77 | |||
78 | /** |
||
79 | * {@inheritdoc} |
||
80 | */ |
||
81 | public function key() { |
||
84 | |||
85 | /** |
||
86 | * {@inheritdoc} |
||
87 | */ |
||
88 | 4 | public function valid() { |
|
99 | |||
100 | /** |
||
101 | * {@inheritdoc} |
||
102 | */ |
||
103 | 4 | public function rewind() { |
|
110 | |||
111 | /** |
||
112 | * {@inheritdoc} |
||
113 | */ |
||
114 | 4 | public function count() { |
|
123 | |||
124 | /** |
||
125 | * Convert the iterator into an array. |
||
126 | * |
||
127 | * @return array |
||
128 | * The elements. |
||
129 | */ |
||
130 | 4 | View Code Duplication | public function toArray() { |
139 | |||
140 | } |
||
141 |