Completed
Push — master ( 321c29...f7acb7 )
by Peter
05:07
created

UniqueModelsAwareTrait   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 94
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 71.43%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
lcom 1
cbo 0
dl 0
loc 94
ccs 20
cts 28
cp 0.7143
rs 10
c 1
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getModels() 0 4 1
A setModels() 0 16 2
A addModel() 0 9 2
A removeModel() 0 18 4
A hasModel() 0 11 3
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 38
	public function getModels()
28
	{
29 38
		return $this->models;
30
	}
31
32
	/**
33
	 *
34
	 * @param AnnotatedInterface[] $models
35
	 * @return $this
36
	 */
37
	public function setModels($models)
38
	{
39
		// Unique based on class name
40
		// See: http://stackoverflow.com/a/2561283/5444623
41 38
		$map = function($value)
42
		{
43 38
			if (is_object($value))
44
			{
45 38
				return get_class($value);
46
			}
47 3
			return $value;
48 38
		};
49 38
		$unique = array_intersect_key($models, array_unique(array_map($map, $models)));
50 38
		$this->models = array_values($unique);
51 38
		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 38
	public function addModel(AnnotatedInterface $model)
61
	{
62 38
		if (!$this->hasModel($model))
63
		{
64 19
			$this->models[] = $model;
65 19
			return true;
66
		}
67 32
		return false;
68
	}
69
70
	/**
71
	 * Remove model from set.
72
	 *
73
	 * @param AnnotatedInterface $model
74
	 * @return boolean Whether model was removed
75
	 */
76
	public function removeModel(AnnotatedInterface $model)
77
	{
78
		if (!$this->hasModel($model))
79
		{
80
			return false;
81
		}
82
		foreach ($this->models as $index => $existing)
83
		{
84
			if (get_class($existing) === get_class($model))
85
			{
86
				unset($this->models[$index]);
87
				return true;
88
			}
89
		}
90
91
		// Should not happen, model not found even if should exists
92
		return false;
93
	}
94
95 38
	public function hasModel(AnnotatedInterface $model)
96
	{
97 38
		foreach ($this->models as $existing)
98
		{
99 34
			if (get_class($existing) === get_class($model))
100
			{
101 34
				return true;
102
			}
103
		}
104 19
		return false;
105
	}
106
107
}
108