1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CompoLab\Domain\Utils; |
4
|
|
|
|
5
|
|
|
trait JsonConvertibleTrait |
6
|
|
|
{ |
7
|
|
|
/** @var array */ |
8
|
|
|
private $objPropertiesCache = []; |
9
|
|
|
|
10
|
|
|
/** @var array */ |
11
|
|
|
private $objArrayHiddenKeys = [ |
12
|
|
|
'objPropertiesCache', |
13
|
|
|
'objArrayHiddenKeys', |
14
|
|
|
]; |
15
|
|
|
|
16
|
3 |
|
private function hideArrayKey($key) |
17
|
|
|
{ |
18
|
3 |
|
$this->objArrayHiddenKeys[] = $key; |
19
|
3 |
|
} |
20
|
|
|
|
21
|
|
|
public function offsetExists($offset) |
22
|
|
|
{ |
23
|
|
|
return isset($this->$offset); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function offsetGet($offset) |
27
|
|
|
{ |
28
|
|
|
if (!isset($this->$offset)) { |
29
|
|
|
throw new \RuntimeException(sprintf('There is no "%s" property on object %s', $offset, get_class($this))); |
30
|
|
|
} |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function offsetSet(/** @scrutinizer ignore-unused */ $offset, /** @scrutinizer ignore-unused */ $value) |
34
|
|
|
{ |
35
|
|
|
throw new \RuntimeException('Array access is read-only'); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function offsetUnset(/** @scrutinizer ignore-unused */ $offset) |
39
|
|
|
{ |
40
|
|
|
throw new \RuntimeException('Array access is read-only'); |
41
|
|
|
} |
42
|
|
|
|
43
|
5 |
|
public function getIterator() |
44
|
|
|
{ |
45
|
5 |
|
return new \ArrayIterator($this->getObjectProperties()); |
46
|
|
|
} |
47
|
|
|
|
48
|
5 |
|
private function getObjectProperties(): array |
49
|
|
|
{ |
50
|
5 |
|
if (!empty($this->objPropertiesCache)) { |
51
|
1 |
|
return $this->objPropertiesCache; |
52
|
|
|
} |
53
|
|
|
|
54
|
5 |
|
$reflection = new \ReflectionClass(self::class); |
55
|
|
|
|
56
|
5 |
|
$properties = []; |
57
|
5 |
|
foreach ($reflection->getProperties() as $property) { |
58
|
5 |
|
if (in_array($property->getName(), $this->objArrayHiddenKeys)) { |
59
|
5 |
|
continue; |
60
|
|
|
} |
61
|
|
|
|
62
|
5 |
|
$property->setAccessible(true); |
63
|
5 |
|
$properties[$property->getName()] = $property->getValue($this); |
64
|
|
|
} |
65
|
|
|
|
66
|
5 |
|
return $this->objPropertiesCache = $properties; |
67
|
|
|
} |
68
|
|
|
|
69
|
3 |
|
public function jsonSerialize() |
70
|
|
|
{ |
71
|
3 |
|
return array_filter($this->_toArray()); |
72
|
|
|
} |
73
|
|
|
|
74
|
5 |
|
public function _toArray(): array |
75
|
|
|
{ |
76
|
5 |
|
$array = []; |
77
|
5 |
|
foreach ($this as $key => $value) { |
78
|
5 |
|
if ($value instanceof JsonConvertible) { |
79
|
|
|
$array[$key] = $value->_toArray(); |
80
|
|
|
|
81
|
5 |
|
} elseif (is_object($value) and method_exists($value, '__toString')) { |
82
|
5 |
|
$array[$key] = (string) $value; |
83
|
|
|
|
84
|
|
|
} else { |
85
|
5 |
|
$array[$key] = $value; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
89
|
5 |
|
return $array; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|