|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Chubbyphp\Model\Collection; |
|
6
|
|
|
|
|
7
|
|
|
use Chubbyphp\Model\ModelInterface; |
|
8
|
|
|
|
|
9
|
|
|
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
|
|
|
$models = $this->modelsWithIdKey($models); |
|
27
|
|
|
|
|
28
|
|
|
$this->initialModels = $models; |
|
29
|
|
|
$this->models = $models; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* @param ModelInterface[]|array $models |
|
34
|
|
|
* |
|
35
|
|
|
* @return ModelInterface[]|array |
|
36
|
|
|
*/ |
|
37
|
|
View Code Duplication |
private function modelsWithIdKey(array $models): array |
|
|
|
|
|
|
38
|
|
|
{ |
|
39
|
|
|
$modelsWithIdKey = []; |
|
40
|
|
|
foreach ($models as $model) { |
|
41
|
|
|
if (!$model instanceof ModelInterface) { |
|
42
|
|
|
throw new \InvalidArgumentException( |
|
43
|
|
|
sprintf('Model with index %d needs to implement: %s', ModelInterface::class) |
|
44
|
|
|
); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
$modelsWithIdKey[$model->getId()] = $model; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
return $modelsWithIdKey; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* @param ModelInterface[]|array $models |
|
55
|
|
|
*/ |
|
56
|
|
|
public function set(array $models) |
|
57
|
|
|
{ |
|
58
|
|
|
$this->models = $this->modelsWithIdKey($models); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* @return ModelInterface[]|array |
|
63
|
|
|
*/ |
|
64
|
|
|
public function get(): array |
|
65
|
|
|
{ |
|
66
|
|
|
return $this->models; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* @return ModelInterface[]|array |
|
71
|
|
|
*/ |
|
72
|
|
|
public function getInitial(): array |
|
73
|
|
|
{ |
|
74
|
|
|
return $this->initialModels; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
/** |
|
78
|
|
|
* @return array |
|
79
|
|
|
*/ |
|
80
|
|
|
public function jsonSerialize(): array |
|
81
|
|
|
{ |
|
82
|
|
|
$serializedModels = []; |
|
83
|
|
|
foreach ($this->models as $model) { |
|
84
|
|
|
$serializedModels[] = $model->jsonSerialize(); |
|
85
|
|
|
} |
|
86
|
|
|
|
|
87
|
|
|
return $serializedModels; |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|
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.