1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Remorhaz\JSON\Data\Value\DecodedJson; |
5
|
|
|
|
6
|
|
|
use Generator; |
7
|
|
|
use Iterator; |
8
|
|
|
use Remorhaz\JSON\Data\Value\ArrayValueInterface; |
9
|
|
|
use Remorhaz\JSON\Data\Event\AfterArrayEvent; |
10
|
|
|
use Remorhaz\JSON\Data\Event\BeforeArrayEvent; |
11
|
|
|
use Remorhaz\JSON\Data\Event\ElementEvent; |
12
|
|
|
use Remorhaz\JSON\Data\Path\PathInterface; |
13
|
|
|
use Remorhaz\JSON\Data\Value\NodeValueInterface; |
14
|
|
|
|
15
|
|
|
final class NodeArrayValue implements NodeValueInterface, ArrayValueInterface |
16
|
|
|
{ |
17
|
|
|
|
18
|
|
|
private $data; |
19
|
|
|
|
20
|
|
|
private $path; |
21
|
|
|
|
22
|
|
|
private $valueFactory; |
23
|
|
|
|
24
|
5 |
|
public function __construct( |
25
|
|
|
array $data, |
26
|
|
|
PathInterface $path, |
27
|
|
|
NodeValueFactoryInterface $valueFactory |
28
|
|
|
) { |
29
|
5 |
|
$this->data = $data; |
30
|
5 |
|
$this->path = $path; |
31
|
5 |
|
$this->valueFactory = $valueFactory; |
32
|
5 |
|
} |
33
|
|
|
|
34
|
3 |
|
public function createChildIterator(): Iterator |
35
|
|
|
{ |
36
|
3 |
|
return $this->createChildGenerator(); |
37
|
|
|
} |
38
|
|
|
|
39
|
3 |
|
private function createChildGenerator(): Generator |
40
|
|
|
{ |
41
|
3 |
|
$validIndex = 0; |
42
|
3 |
|
foreach ($this->data as $index => $element) { |
43
|
2 |
|
if ($index !== $validIndex++) { |
44
|
|
|
throw new Exception\InvalidElementKeyException($index, $this->path); |
45
|
|
|
} |
46
|
|
|
yield $this |
47
|
2 |
|
->valueFactory |
48
|
2 |
|
->createValue($element, $this->path->copyWithElement($index)); |
49
|
|
|
} |
50
|
3 |
|
} |
51
|
|
|
|
52
|
5 |
|
public function createEventIterator(): Iterator |
53
|
|
|
{ |
54
|
5 |
|
return $this->createEventGenerator($this->data, $this->path); |
55
|
|
|
} |
56
|
|
|
|
57
|
5 |
|
private function createEventGenerator(array $data, PathInterface $path): Generator |
58
|
|
|
{ |
59
|
5 |
|
yield new BeforeArrayEvent($this); |
60
|
|
|
|
61
|
5 |
|
$validIndex = 0; |
62
|
5 |
|
foreach ($data as $index => $element) { |
63
|
4 |
|
if ($index !== $validIndex++) { |
64
|
2 |
|
throw new Exception\InvalidElementKeyException($index, $path); |
65
|
|
|
} |
66
|
2 |
|
yield new ElementEvent($index, $path); |
67
|
|
|
yield from $this |
68
|
2 |
|
->valueFactory |
69
|
2 |
|
->createValue($element, $path->copyWithElement($index)) |
70
|
2 |
|
->createEventIterator(); |
71
|
|
|
} |
72
|
|
|
|
73
|
3 |
|
yield new AfterArrayEvent($this); |
74
|
3 |
|
} |
75
|
|
|
|
76
|
3 |
|
public function getPath(): PathInterface |
77
|
|
|
{ |
78
|
3 |
|
return $this->path; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|