1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Maslosoft\Manganel\Traits; |
4
|
|
|
|
5
|
|
|
use Maslosoft\Addendum\Interfaces\AnnotatedInterface; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Use this trait to provide mutli-model feature to classes. |
9
|
|
|
* |
10
|
|
|
* NOTE: It will keep only one instance type in models |
11
|
|
|
* |
12
|
|
|
* @author Piotr Maselkowski <pmaselkowski at gmail.com> |
13
|
|
|
*/ |
14
|
|
|
trait UniqueModelsAwareTrait |
15
|
|
|
{ |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Annotated model |
19
|
|
|
* @var AnnotatedInterface[] |
20
|
|
|
*/ |
21
|
|
|
private $models = []; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Annotated models |
25
|
|
|
* @var AnnotatedInterface[] |
26
|
|
|
*/ |
27
|
3 |
|
public function getModels() |
28
|
|
|
{ |
29
|
3 |
|
return $this->models; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* |
34
|
|
|
* @param AnnotatedInterface[] $models |
35
|
|
|
* @return $this |
36
|
|
|
*/ |
37
|
4 |
|
public function setModels($models) |
38
|
|
|
{ |
39
|
|
|
// Unique based on class name |
40
|
|
|
// See: http://stackoverflow.com/a/2561283/5444623 |
41
|
4 |
|
$unique = array_intersect_key($models, array_unique(array_map('get_class', $models))); |
42
|
4 |
|
$this->models = array_values($unique); |
43
|
4 |
|
return $this; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Add model to set but only if it's instance is not present in set. |
48
|
|
|
* |
49
|
|
|
* @param AnnotatedInterface $model |
50
|
|
|
* @return boolean Whether model was added |
51
|
|
|
*/ |
52
|
|
|
public function addModel(AnnotatedInterface $model) |
53
|
|
|
{ |
54
|
|
|
if (!$this->hasModel($model)) |
55
|
|
|
{ |
56
|
|
|
$this->models[] = $model; |
57
|
|
|
return true; |
58
|
|
|
} |
59
|
|
|
return false; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Remove model from set. |
64
|
|
|
* |
65
|
|
|
* @param AnnotatedInterface $model |
66
|
|
|
* @return boolean Whether model was removed |
67
|
|
|
*/ |
68
|
|
|
public function removeModel(AnnotatedInterface $model) |
69
|
|
|
{ |
70
|
|
|
if (!$this->hasModel($model)) |
71
|
|
|
{ |
72
|
|
|
return false; |
73
|
|
|
} |
74
|
|
|
foreach ($this->models as $index => $existing) |
75
|
|
|
{ |
76
|
|
|
if (get_class($existing) === get_class($model)) |
77
|
|
|
{ |
78
|
|
|
unset($this->models[$index]); |
79
|
|
|
return true; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
// Should not happen, model not found even if should exists |
84
|
|
|
return false; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
public function hasModel(AnnotatedInterface $model) |
88
|
|
|
{ |
89
|
|
|
foreach ($this->models as $existing) |
90
|
|
|
{ |
91
|
|
|
if (get_class($existing) === get_class($model)) |
92
|
|
|
{ |
93
|
|
|
return true; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
return false; |
97
|
|
|
} |
98
|
|
|
|
99
|
|
|
} |
100
|
|
|
|