1
|
|
|
<?php declare(strict_types=1); |
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 $data |
22
|
|
|
*/ |
23
|
|
|
trait AccessorTrait |
24
|
|
|
{ |
25
|
13 |
|
public function &__get($index) |
26
|
|
|
{ |
27
|
13 |
|
if (false === array_key_exists($index, $this->data)) { |
28
|
5 |
|
$this->data[$index] = null; |
29
|
|
|
} |
30
|
13 |
|
return $this->data[$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
|
8 |
|
public function get(string $index, mixed $default = null): mixed |
49
|
|
|
{ |
50
|
8 |
|
return $this->data[$index] ?? $default; |
51
|
|
|
} |
52
|
|
|
|
53
|
5 |
|
public function has(string $index): bool |
54
|
|
|
{ |
55
|
5 |
|
return array_key_exists($index, $this->data); |
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->data); |
66
|
|
|
} |
67
|
|
|
|
68
|
23 |
|
public function toArray(): array |
69
|
|
|
{ |
70
|
23 |
|
return $this->data; |
71
|
|
|
} |
72
|
|
|
|
73
|
1 |
|
public function toJSON(int $options = 0): string |
74
|
|
|
{ |
75
|
1 |
|
return json_serialize($this->data, $options); |
76
|
|
|
} |
77
|
|
|
|
78
|
1 |
|
public function toXML(string $root): string |
79
|
|
|
{ |
80
|
1 |
|
return xml_serialize($root, $this->data); |
81
|
|
|
} |
82
|
|
|
|
83
|
4 |
|
public function getIterator(): Traversable |
84
|
|
|
{ |
85
|
4 |
|
foreach ($this->data as $k => $v) { |
86
|
3 |
|
yield $k => $v; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|
90
|
1 |
|
public function jsonSerialize(): mixed |
91
|
|
|
{ |
92
|
1 |
|
return $this->data; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|