1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Koded package. |
5
|
|
|
* |
6
|
|
|
* (c) Mihail Binev <[email protected]> |
7
|
|
|
* |
8
|
|
|
* Please view the LICENSE distributed with this source code |
9
|
|
|
* for the full copyright and license information. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Koded\Stdlib; |
13
|
|
|
|
14
|
|
|
use Koded\Exceptions\ReadOnlyException; |
15
|
|
|
use Traversable; |
16
|
|
|
use function array_key_exists; |
17
|
|
|
use function count; |
18
|
|
|
use function get_class; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @property array $storage |
22
|
|
|
*/ |
23
|
|
|
trait AccessorTrait |
24
|
|
|
{ |
25
|
12 |
|
public function & __get($index) |
26
|
|
|
{ |
27
|
12 |
|
if (false === array_key_exists($index, $this->storage)) { |
28
|
5 |
|
$this->storage[$index] = null; |
29
|
|
|
} |
30
|
12 |
|
return $this->storage[$index]; |
31
|
|
|
} |
32
|
|
|
|
33
|
1 |
|
public function __set($index, $value) |
34
|
|
|
{ |
35
|
1 |
|
throw ReadOnlyException::forInstance($index, get_class($this)); |
36
|
|
|
} |
37
|
|
|
|
38
|
1 |
|
public function __clone() |
39
|
|
|
{ |
40
|
1 |
|
throw ReadOnlyException::forCloning(get_class($this)); |
41
|
|
|
} |
42
|
|
|
|
43
|
1 |
|
public function __isset($index) |
44
|
|
|
{ |
45
|
1 |
|
return $this->has($index); |
46
|
|
|
} |
47
|
|
|
|
48
|
5 |
|
public function get(string $index, mixed $default = null): mixed |
49
|
|
|
{ |
50
|
5 |
|
return $this->storage[$index] ?? $default; |
51
|
|
|
} |
52
|
|
|
|
53
|
3 |
|
public function has(mixed $index): bool |
54
|
|
|
{ |
55
|
3 |
|
return array_key_exists($index, $this->storage); |
56
|
|
|
} |
57
|
|
|
|
58
|
1 |
|
public function equals(string $propertyA, string $propertyB): bool |
59
|
|
|
{ |
60
|
1 |
|
return $this->get($propertyA) === $this->get($propertyB); |
61
|
|
|
} |
62
|
|
|
|
63
|
2 |
|
public function count(): int |
64
|
|
|
{ |
65
|
2 |
|
return count($this->storage); |
66
|
|
|
} |
67
|
|
|
|
68
|
18 |
|
public function toArray(): array |
69
|
|
|
{ |
70
|
18 |
|
return $this->storage; |
71
|
|
|
} |
72
|
|
|
|
73
|
1 |
|
public function toJSON(int $options = 0): string |
74
|
|
|
{ |
75
|
1 |
|
return json_serialize($this->storage, $options); |
76
|
|
|
} |
77
|
|
|
|
78
|
1 |
|
public function toXML(string $root): string |
79
|
|
|
{ |
80
|
1 |
|
return xml_serialize($root, $this->storage); |
81
|
|
|
} |
82
|
|
|
|
83
|
3 |
|
public function getIterator(): Traversable |
84
|
|
|
{ |
85
|
3 |
|
foreach ($this->storage as $k => $v) { |
86
|
3 |
|
yield $k => $v; |
87
|
|
|
} |
88
|
3 |
|
} |
89
|
|
|
|
90
|
1 |
|
public function jsonSerialize(): array |
91
|
|
|
{ |
92
|
1 |
|
return $this->storage; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|