1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace hiqdev\higrid\representations; |
4
|
|
|
|
5
|
|
|
use Yii; |
6
|
|
|
use yii\base\Exception; |
7
|
|
|
use yii\base\InvalidConfigException; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class RepresentationCollection represents a collection of [[Representation]] objects |
11
|
|
|
* and provides API to access them. |
12
|
|
|
* |
13
|
|
|
* @author Dmytro Naumenko <[email protected]> |
14
|
|
|
*/ |
15
|
|
|
class RepresentationCollection implements RepresentationCollectionInterface |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* RepresentationCollection constructor. |
19
|
|
|
*/ |
20
|
|
|
public function __construct() |
21
|
|
|
{ |
22
|
|
|
$this->fillRepresentations(); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var array |
27
|
|
|
*/ |
28
|
|
|
protected $representations = []; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @void |
32
|
|
|
*/ |
33
|
|
|
protected function fillRepresentations() |
34
|
|
|
{ |
35
|
|
|
$this->representations = []; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* {@inheritdoc} |
40
|
|
|
*/ |
41
|
|
|
public function getAll() |
42
|
|
|
{ |
43
|
|
|
foreach ($this->representations as $name => $representation) { |
44
|
|
|
if (!is_object($representation)) { |
45
|
|
|
$representation = $this->representations[$name] = Yii::createObject(array_merge([ |
46
|
|
|
'class' => Representation::class |
47
|
|
|
], $representation)); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
if (!$representation instanceof RepresentationInterface) { |
51
|
|
|
throw new InvalidConfigException('Representation "' . $name .'" must be instance of RepresentationInterface'); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return $this->representations; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* {@inheritdoc} |
60
|
|
|
*/ |
61
|
|
|
public function getByName($name) |
62
|
|
|
{ |
63
|
|
|
if (!$this->exists($name)) { |
64
|
|
|
$this->getDefault(); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $this->getAll()[$name]; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* {@inheritdoc} |
72
|
|
|
*/ |
73
|
|
|
public function getDefault() |
74
|
|
|
{ |
75
|
|
|
if (count($this->getAll()) === 0) { |
76
|
|
|
throw new InvalidConfigException('Default can not be applied because collection is empty.'); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return reset($this->getAll()); |
|
|
|
|
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* {@inheritdoc} |
84
|
|
|
*/ |
85
|
|
|
public function exists($name) |
86
|
|
|
{ |
87
|
|
|
return isset($this->getAll()[$name]); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|