Passed
Push — master ( 4f4697...c69a90 )
by Edward
04:40
created

NodeArrayValue::createEventIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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