Passed
Push — master ( df5d45...c16c79 )
by Edward
05:03
created

ValueFetcher::fetchValueDeepChildren()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
nc 3
nop 2
dl 0
loc 13
ccs 0
cts 6
cp 0
crap 12
rs 10
c 1
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Remorhaz\JSON\Path\Runtime;
5
6
use Generator;
7
use Iterator;
8
use Remorhaz\JSON\Data\Value\StructValueInterface;
9
use Remorhaz\JSON\Data\Value\NodeValueInterface;
10
use Remorhaz\JSON\Data\Value\ScalarValueInterface;
11
12
final class ValueFetcher implements ValueFetcherInterface
13
{
14
15
    /**
16
     * @param Matcher\ChildMatcherInterface $matcher
17
     * @param NodeValueInterface $value
18
     * @return NodeValueInterface[]|Iterator
19
     */
20
    public function createChildrenIterator(
21
        Matcher\ChildMatcherInterface $matcher,
22
        NodeValueInterface $value
23
    ): Iterator {
24
        return $this->createChildrenGenerator($matcher, $value);
25
    }
26
27
    private function createChildrenGenerator(
28
        Matcher\ChildMatcherInterface $matcher,
29
        NodeValueInterface $value
30
    ): Generator {
31
        if ($value instanceof ScalarValueInterface) {
32
            return;
33
        }
34
35
        if ($value instanceof StructValueInterface) {
36
            foreach ($value->createChildIterator() as $index => $element) {
37
                if ($matcher->match($index, $element, $value)) {
38
                    yield $element;
39
                }
40
            }
41
            return;
42
        }
43
44
        throw new Exception\UnexpectedNodeValueFetchedException($value);
45
    }
46
47
    public function createDeepChildrenIterator(
48
        Matcher\ChildMatcherInterface $matcher,
49
        NodeValueInterface $value
50
    ): Iterator {
51
        return $this->createDeepChildrenGenerator($matcher, $value);
52
    }
53
54
    private function createDeepChildrenGenerator(
55
        Matcher\ChildMatcherInterface $matcher,
56
        NodeValueInterface $value
57
    ): Generator {
58
        if ($value instanceof ScalarValueInterface) {
59
            return;
60
        }
61
62
        if ($value instanceof StructValueInterface) {
63
            foreach ($value->createChildIterator() as $index => $element) {
64
                if ($matcher->match($index, $element, $value)) {
65
                    yield $element;
66
                }
67
                yield from $this->createDeepChildrenGenerator($matcher, $element);
68
            }
69
            return;
70
        }
71
72
        throw new Exception\UnexpectedNodeValueFetchedException($value);
73
    }
74
}
75