1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace FlyCrud; |
5
|
|
|
|
6
|
|
|
use ArrayObject; |
7
|
|
|
use JsonSerializable; |
8
|
|
|
|
9
|
|
|
class Document extends ArrayObject implements JsonSerializable |
10
|
|
|
{ |
11
|
|
|
public function __construct(array $value) |
12
|
|
|
{ |
13
|
|
|
parent::__construct(self::arrayToObject($value)); |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @return mixed |
18
|
|
|
*/ |
19
|
|
|
public function &__get(string $name) |
20
|
|
|
{ |
21
|
|
|
$value = $this->offsetGet($name); |
22
|
|
|
|
23
|
|
|
return $value; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param mixed $value |
28
|
|
|
*/ |
29
|
|
|
public function __set(string $name, $value) |
30
|
|
|
{ |
31
|
|
|
$this->offsetSet($name, $value); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function __isset(string $name) |
35
|
|
|
{ |
36
|
|
|
return $this->offsetExists($name); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function __unset(string $name) |
40
|
|
|
{ |
41
|
|
|
$this->offsetUnset($name); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @see JsonSerializable |
46
|
|
|
*/ |
47
|
|
|
public function jsonSerialize(): array |
48
|
|
|
{ |
49
|
|
|
return $this->getArrayCopy(); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Returns the document data. |
54
|
|
|
*/ |
55
|
|
|
public function getArrayCopy(): array |
56
|
|
|
{ |
57
|
|
|
return self::objectToArray(parent::getArrayCopy()); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Converts the associative arrays to stdClass object recursively. |
62
|
|
|
* |
63
|
|
|
* @return array|stdClass |
64
|
|
|
*/ |
65
|
|
|
private static function arrayToObject(array $array) |
66
|
|
|
{ |
67
|
|
|
$is_object = false; |
68
|
|
|
|
69
|
|
|
foreach ($array as $key => &$value) { |
70
|
|
|
if (is_array($value)) { |
71
|
|
|
$value = self::arrayToObject($value); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
if (is_string($key)) { |
75
|
|
|
$is_object = true; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return $is_object ? (object) $array : $array; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* Converts stdClass objects to arrays recursively. |
84
|
|
|
*/ |
85
|
|
|
private static function objectToArray(array $array): array |
86
|
|
|
{ |
87
|
|
|
foreach ($array as $key => &$value) { |
88
|
|
|
if (is_object($value) || is_array($value)) { |
89
|
|
|
$value = self::objectToArray((array) $value); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
return (array) $array; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|