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 { |
||
13 | |||
14 | /** |
||
15 | * @var int |
||
16 | */ |
||
17 | protected $key; |
||
18 | |||
19 | /** |
||
20 | * @var \Iterator[] |
||
21 | */ |
||
22 | protected $iterators = array(); |
||
23 | |||
24 | /** |
||
25 | * Product constructor. |
||
26 | * |
||
27 | * @param array $datasetArray |
||
28 | * @param int|null $length |
||
29 | */ |
||
30 | 4 | public function __construct(array $datasetArray, $length = NULL) { |
|
1 ignored issue
–
show
|
|||
31 | 4 | parent::__construct($datasetArray); |
|
32 | |||
33 | 4 | foreach ($datasetArray as $dataset) { |
|
34 | 4 | $this->iterators[] = new \ArrayIterator($dataset); |
|
35 | } |
||
36 | |||
37 | 4 | $this->key = 0; |
|
38 | 4 | } |
|
39 | |||
40 | /** |
||
41 | * @inheritdoc |
||
42 | */ |
||
43 | 4 | public function current() { |
|
44 | 4 | $tuple = array(); |
|
45 | |||
46 | 4 | foreach ($this->iterators as $iterator) { |
|
47 | 4 | $tuple[] = $iterator->current(); |
|
48 | } |
||
49 | |||
50 | 4 | return $tuple; |
|
51 | } |
||
52 | |||
53 | /** |
||
54 | * @inheritdoc |
||
55 | */ |
||
56 | 4 | public function next() { |
|
57 | /** @var $reverseIterators \Iterator[] */ |
||
58 | 4 | $reverseIterators = array_reverse($this->iterators); |
|
59 | |||
60 | 4 | foreach ($reverseIterators as $key => $iterator) { |
|
61 | 4 | $iterator->next(); |
|
62 | 4 | if ($iterator->valid()) { |
|
63 | 4 | foreach ($this->iterators as $key2 => $iterator2) { |
|
64 | 4 | if ($key >= count($this->iterators) - $key2) { |
|
65 | 4 | $iterator2->rewind(); |
|
66 | } |
||
67 | } |
||
68 | 4 | break; |
|
69 | } |
||
70 | } |
||
71 | |||
72 | 4 | $this->key++; |
|
73 | 4 | } |
|
74 | |||
75 | /** |
||
76 | * @inheritdoc |
||
77 | */ |
||
78 | public function key() { |
||
81 | |||
82 | /** |
||
83 | * @inheritdoc |
||
84 | */ |
||
85 | 4 | public function valid() { |
|
96 | |||
97 | /** |
||
98 | * @inheritdoc |
||
99 | */ |
||
100 | 4 | public function rewind() { |
|
107 | |||
108 | /** |
||
109 | * @return int |
||
110 | */ |
||
111 | 4 | public function count() { |
|
120 | |||
121 | /** |
||
122 | * @return array |
||
123 | */ |
||
124 | 4 | View Code Duplication | public function toArray() { |
133 | |||
134 | } |
||
135 |