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 | final class ModelCollection implements ModelCollectionInterface |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * @var ModelInterface[]|array |
||
| 13 | */ |
||
| 14 | private $initialModels; |
||
| 15 | |||
| 16 | /** |
||
| 17 | * @var ModelInterface[]|array |
||
| 18 | */ |
||
| 19 | private $models; |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @param ModelInterface[]|array $models |
||
| 23 | */ |
||
| 24 | public function __construct(array $models = []) |
||
| 25 | { |
||
| 26 | $this->setModels($models); |
||
| 27 | $this->initialModels = $this->models; |
||
| 28 | } |
||
| 29 | |||
| 30 | /** |
||
| 31 | * @param ModelInterface $model |
||
| 32 | * @return ModelCollectionInterface |
||
| 33 | */ |
||
| 34 | public function addModel(ModelInterface $model): ModelCollectionInterface |
||
| 35 | { |
||
| 36 | $this->models[$model->getId()] = $model; |
||
| 37 | |||
| 38 | return $this; |
||
| 39 | } |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @param ModelInterface $model |
||
| 43 | * @return ModelCollectionInterface |
||
| 44 | */ |
||
| 45 | public function removeModel(ModelInterface $model): ModelCollectionInterface |
||
| 46 | { |
||
| 47 | if (isset($this->models[$model->getId()])) { |
||
| 48 | unset($this->models[$model->getId()); |
||
|
|
|||
| 49 | } |
||
| 50 | |||
| 51 | return $this; |
||
| 52 | } |
||
| 53 | |||
| 54 | /** |
||
| 55 | * @param ModelInterface[]|array $models |
||
| 56 | * @return ModelCollectionInterface |
||
| 57 | */ |
||
| 58 | public function setModels(array $models): ModelCollectionInterface |
||
| 59 | { |
||
| 60 | $this->models = []; |
||
| 61 | foreach ($models as $model) { |
||
| 62 | $this->addModel($model); |
||
| 63 | } |
||
| 64 | |||
| 65 | return $this; |
||
| 66 | } |
||
| 67 | |||
| 68 | /** |
||
| 69 | * @return ModelInterface[]|array |
||
| 70 | */ |
||
| 71 | public function getModels(): array |
||
| 72 | { |
||
| 73 | return $this->models; |
||
| 74 | } |
||
| 75 | |||
| 76 | /** |
||
| 77 | * @return ModelInterface[]|array |
||
| 78 | */ |
||
| 79 | public function getInitialModels(): array |
||
| 80 | { |
||
| 81 | return $this->initialModels; |
||
| 82 | } |
||
| 83 | |||
| 84 | /** |
||
| 85 | * @return array |
||
| 86 | */ |
||
| 87 | public function jsonSerialize(): array |
||
| 88 | { |
||
| 89 | $serializedModels = []; |
||
| 90 | foreach ($this->models as $model) { |
||
| 97 |