1
1
<?php
2
2
namespace Gt \Fetch \Response ;
3
3
4
+ use ArrayAccess ;
5
+ use Iterator ;
4
6
use StdClass ;
5
7
6
- class Json extends StdClass {
8
+ class Json extends StdClass implements ArrayAccess, Iterator {
9
+ protected $ jsonObject ;
10
+ protected $ iteratorKey ;
11
+ protected $ iteratorProperties ;
7
12
13
+ public function __construct ($ jsonObject ) {
14
+ $ this ->jsonObject = $ jsonObject ;
15
+
16
+ $ this ->iteratorKey = 0 ;
17
+
18
+ if (is_array ($ jsonObject )) {
19
+ $ this ->iteratorProperties = array_keys ($ jsonObject );
20
+ }
21
+ else {
22
+ $ this ->iteratorProperties = get_object_vars ($ jsonObject );
23
+ }
24
+
25
+ }
26
+
27
+ public function __get (string $ key ) {
28
+ return $ this ->jsonObject ->$ key ;
29
+ }
30
+
31
+ /** @link https://php.net/manual/en/arrayaccess.offsetexists.php */
32
+ public function offsetExists ($ offset ):bool {
33
+ return isset ($ this ->jsonObject [$ offset ]);
34
+ }
35
+
36
+ /** @link https://php.net/manual/en/arrayaccess.offsetget.php */
37
+ public function offsetGet ($ offset ) {
38
+ return $ this ->jsonObject [$ offset ];
39
+ }
40
+
41
+ /** @link https://php.net/manual/en/arrayaccess.offsetset.php */
42
+ public function offsetSet ($ offset , $ value ):void {
43
+ $ this ->jsonObject [$ offset ] = $ value ;
44
+ }
45
+
46
+ /** @link https://php.net/manual/en/arrayaccess.offsetunset.php */
47
+ public function offsetUnset ($ offset ):void {
48
+ unset($ this ->jsonObject [$ offset ]);
49
+ }
50
+
51
+ /** @link https://php.net/manual/en/iterator.current.php */
52
+ public function current () {
53
+ if (is_array ($ this ->jsonObject )) {
54
+ return $ this ->jsonObject [$ this ->iteratorKey ];
55
+ }
56
+
57
+ $ property = $ this ->iteratorProperties [$ this ->iteratorKey ];
58
+ return $ this ->jsonObject ->{$ property };
59
+ }
60
+
61
+ /** @link https://php.net/manual/en/iterator.next.php */
62
+ public function next ():void {
63
+ $ this ->iteratorKey ++;
64
+ }
65
+
66
+ /** @link https://php.net/manual/en/iterator.key.php */
67
+ public function key () {
68
+ if (is_array ($ this ->jsonObject )) {
69
+ return $ this ->iteratorKey ;
70
+ }
71
+
72
+ return $ this ->iteratorProperties [$ this ->iteratorKey ];
73
+ }
74
+
75
+ /** @link https://php.net/manual/en/iterator.valid.php */
76
+ public function valid () {
77
+ if (is_array ($ this ->jsonObject )) {
78
+ return isset ($ this ->jsonObject [$ this ->iteratorKey ]);
79
+ }
80
+
81
+ $ property = $ this ->iteratorProperties [$ this ->iteratorKey ];
82
+ return isset ($ this ->jsonObject ->{$ property });
83
+ }
84
+
85
+ /** @link https://php.net/manual/en/iterator.rewind.php */
86
+ public function rewind () {
87
+ $ this ->iteratorKey = 0 ;
88
+ }
8
89
}
0 commit comments