1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This software package is licensed under `AGPL-3.0-only, proprietary` license[s]. |
5
|
|
|
* |
6
|
|
|
* @package maslosoft/manganel |
7
|
|
|
* @license AGPL-3.0-only, proprietary |
8
|
|
|
* |
9
|
|
|
* @copyright Copyright (c) Peter Maselkowski <[email protected]> |
10
|
|
|
* @link https://maslosoft.com/manganel/ |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
namespace Maslosoft\Manganel\Traits; |
14
|
|
|
|
15
|
|
|
use Maslosoft\Addendum\Interfaces\AnnotatedInterface; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Use this trait to provide mutli-model feature to classes. |
19
|
|
|
* |
20
|
|
|
* NOTE: It will not check for uniqueness of models |
21
|
|
|
* Use this if uniqueness is ensured already |
22
|
|
|
* |
23
|
|
|
* @author Piotr Maselkowski <pmaselkowski at gmail.com> |
24
|
|
|
*/ |
25
|
|
|
trait ModelsAwareTrait |
26
|
|
|
{ |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Annotated model |
30
|
|
|
* @var AnnotatedInterface[] |
31
|
|
|
*/ |
32
|
|
|
private $models = []; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Annotated models |
36
|
|
|
* @var AnnotatedInterface[] |
37
|
|
|
*/ |
38
|
|
|
public function getModels() |
39
|
|
|
{ |
40
|
|
|
return $this->models; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* |
45
|
|
|
* @param AnnotatedInterface[] $models |
46
|
|
|
* @return $this |
47
|
|
|
*/ |
48
|
|
|
public function setModels($models) |
49
|
|
|
{ |
50
|
|
|
$this->models = $models; |
51
|
|
|
return $this; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Add model to set but only if it's instance is not present in set. |
56
|
|
|
* |
57
|
|
|
* @param AnnotatedInterface $model |
58
|
|
|
* @return boolean Whether model was added |
59
|
|
|
*/ |
60
|
|
|
public function addModel(AnnotatedInterface $model) |
61
|
|
|
{ |
62
|
|
|
$this->models[] = $model; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Remove model from set. |
67
|
|
|
* |
68
|
|
|
* @param AnnotatedInterface $model |
69
|
|
|
* @return boolean Whether model was removed |
70
|
|
|
*/ |
71
|
|
|
public function removeModel(AnnotatedInterface $model) |
72
|
|
|
{ |
73
|
|
|
if (!$this->hasModel($model)) |
74
|
|
|
{ |
75
|
|
|
return false; |
76
|
|
|
} |
77
|
|
|
foreach ($this->models as $index => $existing) |
78
|
|
|
{ |
79
|
|
|
if (get_class($existing) === get_class($model)) |
80
|
|
|
{ |
81
|
|
|
unset($this->models[$index]); |
82
|
|
|
return true; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
// Should not happen, model not found even if should exists |
87
|
|
|
return false; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
public function hasModel(AnnotatedInterface $model) |
91
|
|
|
{ |
92
|
|
|
foreach ($this->models as $existing) |
93
|
|
|
{ |
94
|
|
|
if (get_class($existing) === get_class($model)) |
95
|
|
|
{ |
96
|
|
|
return true; |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
return false; |
100
|
|
|
} |
101
|
|
|
|
102
|
|
|
} |
103
|
|
|
|