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 |
||
9 | class LazyModelCollection implements ModelCollectionInterface |
||
10 | { |
||
11 | /** |
||
12 | * @var \Closure; |
||
13 | */ |
||
14 | private $resolver; |
||
15 | |||
16 | /** |
||
17 | * @var ModelInterface[]|array |
||
18 | */ |
||
19 | private $initialModels; |
||
20 | |||
21 | /** |
||
22 | * @var ModelInterface[]|array |
||
23 | */ |
||
24 | private $models; |
||
25 | |||
26 | /** |
||
27 | * @param \Closure $resolver |
||
28 | */ |
||
29 | public function __construct(\Closure $resolver) |
||
33 | |||
34 | private function loadModels() |
||
47 | |||
48 | /** |
||
49 | * @param ModelInterface[]|array $models |
||
50 | * |
||
51 | * @return ModelInterface[]|array |
||
52 | */ |
||
53 | View Code Duplication | private function modelsWithIdKey(array $models): array |
|
68 | |||
69 | /** |
||
70 | * @return ModelInterface |
||
71 | */ |
||
72 | public function current() |
||
78 | |||
79 | /** |
||
80 | * @return ModelInterface|false |
||
81 | */ |
||
82 | public function next() |
||
88 | |||
89 | /** |
||
90 | * @return string |
||
91 | */ |
||
92 | public function key() |
||
98 | |||
99 | /** |
||
100 | * @return bool |
||
101 | */ |
||
102 | public function valid() |
||
108 | |||
109 | public function rewind() |
||
115 | |||
116 | /** |
||
117 | * @param ModelInterface[]|array $models |
||
118 | */ |
||
119 | public function set(array $models) |
||
125 | |||
126 | /** |
||
127 | * @return ModelInterface[]|array |
||
128 | */ |
||
129 | public function toPersistence(): array |
||
130 | { |
||
131 | $this->loadModels(); |
||
132 | |||
133 | return $this->models; |
||
134 | } |
||
135 | |||
136 | /** |
||
137 | * @return ModelInterface[]|array |
||
138 | */ |
||
139 | View Code Duplication | public function removeFromPersistence(): array |
|
140 | { |
||
141 | $this->loadModels(); |
||
142 | |||
143 | $removeFromPersistenceModels = []; |
||
144 | foreach ($this->initialModels as $initialModel) { |
||
145 | if (!isset($this->models[$initialModel->getId()])) { |
||
146 | $removeFromPersistenceModels[$initialModel->getId()] = $initialModel; |
||
147 | } |
||
148 | } |
||
149 | |||
150 | return $removeFromPersistenceModels; |
||
151 | } |
||
152 | |||
153 | /** |
||
154 | * @return array |
||
155 | */ |
||
156 | public function jsonSerialize(): array |
||
167 | } |
||
168 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.