1 | <?php |
||
14 | class Store implements ArrayAccess, Countable, IteratorAggregate |
||
15 | { |
||
16 | protected $items = []; |
||
17 | |||
18 | private $className; |
||
19 | |||
20 | /** |
||
21 | * Store constructor. |
||
22 | * |
||
23 | * @param array $data |
||
24 | * @param string $className |
||
25 | * @param string $dataRoot |
||
26 | * @param string $idName |
||
27 | */ |
||
28 | 15 | public function __construct(array $data, $className, $dataRoot, $idName) |
|
29 | { |
||
30 | 15 | $this->className = 'StarCitizen\Models' . $className; |
|
31 | 15 | foreach ($data as $item) { |
|
32 | |||
33 | // Check the data root and idName are good |
||
34 | 15 | $objectData = ($dataRoot != '' ? $item[$dataRoot] : $item); |
|
35 | 15 | $id = ($idName == '' ? null : $objectData[$idName]); |
|
36 | |||
37 | // create the appropriate class and add it to items |
||
38 | 15 | $storageObject = new \ReflectionClass('StarCitizen\Models' . $className); |
|
39 | 15 | $this->offsetSet($id, $storageObject->newInstance($objectData)); |
|
40 | } |
||
41 | 15 | } |
|
42 | |||
43 | /** |
||
44 | * @return ArrayIterator |
||
45 | */ |
||
46 | 13 | public function getIterator() |
|
50 | |||
51 | /** |
||
52 | * @param mixed $offset |
||
53 | * |
||
54 | * @return bool |
||
55 | */ |
||
56 | 5 | public function offsetExists($offset) |
|
57 | { |
||
58 | 5 | if (array_key_exists($offset, $this->items)) |
|
59 | 3 | return true; |
|
60 | |||
61 | 3 | return false; |
|
62 | } |
||
63 | |||
64 | /** |
||
65 | * @param mixed $offset |
||
66 | * |
||
67 | * @return bool|mixed |
||
68 | */ |
||
69 | 3 | public function offsetGet($offset) |
|
70 | { |
||
71 | 3 | if ($this->offsetExists($offset)) |
|
72 | 2 | return $this->items[$offset]; |
|
73 | |||
74 | 1 | return false; |
|
75 | } |
||
76 | |||
77 | /** |
||
78 | * @param mixed $offset |
||
79 | * @param mixed $value |
||
80 | */ |
||
81 | 15 | public function offsetSet($offset, $value) |
|
82 | { |
||
83 | 15 | if ($value instanceof $this->className) |
|
84 | 15 | if ($offset == null) |
|
85 | 1 | $this->items[] = $value; |
|
86 | else |
||
87 | 15 | $this->items[$offset] = $value; |
|
88 | 15 | } |
|
89 | |||
90 | /** |
||
91 | * @param mixed $offset |
||
92 | */ |
||
93 | 1 | public function offsetUnset($offset) |
|
94 | { |
||
95 | 1 | if ($this->offsetExists($offset) && isset($this->items[$offset])) |
|
96 | unset ($this->items[$offset]); |
||
97 | 1 | } |
|
98 | |||
99 | /** |
||
100 | * @return int |
||
101 | */ |
||
102 | 5 | public function count() |
|
106 | |||
107 | /** |
||
108 | * @param $name |
||
109 | * |
||
110 | * @return bool|mixed |
||
111 | */ |
||
112 | 3 | public function __get($name) |
|
116 | |||
117 | /** |
||
118 | * @param $name |
||
119 | * @param $value |
||
120 | */ |
||
121 | 2 | public function __set($name, $value) |
|
125 | |||
126 | /** |
||
127 | * @return string |
||
128 | */ |
||
129 | 1 | public function __toString() |
|
130 | { |
||
133 | } |