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 not check for uniqueness of models |
11
|
|
|
* Use this if uniqueness is ensured already |
12
|
|
|
* |
13
|
|
|
* @author Piotr Maselkowski <pmaselkowski at gmail.com> |
14
|
|
|
*/ |
15
|
|
|
trait ModelsAwareTrait |
16
|
|
|
{ |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Annotated model |
20
|
|
|
* @var AnnotatedInterface[] |
21
|
|
|
*/ |
22
|
|
|
private $models = []; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Annotated models |
26
|
|
|
* @var AnnotatedInterface[] |
27
|
|
|
*/ |
28
|
|
|
public function getModels() |
29
|
|
|
{ |
30
|
|
|
return $this->models; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* |
35
|
|
|
* @param AnnotatedInterface[] $models |
36
|
|
|
* @return $this |
37
|
|
|
*/ |
38
|
|
|
public function setModels($models) |
39
|
|
|
{ |
40
|
|
|
$this->models = $models; |
41
|
|
|
return $this; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Add model to set but only if it's instance is not present in set. |
46
|
|
|
* |
47
|
|
|
* @param AnnotatedInterface $model |
48
|
|
|
* @return boolean Whether model was added |
49
|
|
|
*/ |
50
|
|
|
public function addModel(AnnotatedInterface $model) |
51
|
|
|
{ |
52
|
|
|
$this->models[] = $model; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Remove model from set. |
57
|
|
|
* |
58
|
|
|
* @param AnnotatedInterface $model |
59
|
|
|
* @return boolean Whether model was removed |
60
|
|
|
*/ |
61
|
|
|
public function removeModel(AnnotatedInterface $model) |
62
|
|
|
{ |
63
|
|
|
if (!$this->hasModel($model)) |
64
|
|
|
{ |
65
|
|
|
return false; |
66
|
|
|
} |
67
|
|
|
foreach ($this->models as $index => $existing) |
68
|
|
|
{ |
69
|
|
|
if (get_class($existing) === get_class($model)) |
70
|
|
|
{ |
71
|
|
|
unset($this->models[$index]); |
72
|
|
|
return true; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
// Should not happen, model not found even if should exists |
77
|
|
|
return false; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
public function hasModel(AnnotatedInterface $model) |
81
|
|
|
{ |
82
|
|
|
foreach ($this->models as $existing) |
83
|
|
|
{ |
84
|
|
|
if (get_class($existing) === get_class($model)) |
85
|
|
|
{ |
86
|
|
|
return true; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
return false; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
} |
93
|
|
|
|