Completed
Push — master ( cb0ced...7754cf )
by Edward
04:45
created

NumericAggregator::tryAggregate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 6
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 10
ccs 0
cts 7
cp 0
crap 6
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Remorhaz\JSON\Path\Runtime\Aggregator;
5
6
use function array_map;
7
use function is_float;
8
use function is_int;
9
use Remorhaz\JSON\Data\Value\ArrayValueInterface;
10
use Remorhaz\JSON\Data\Value\ScalarValueInterface;
11
use Remorhaz\JSON\Data\Value\ValueInterface;
12
13
abstract class NumericAggregator implements ValueAggregatorInterface
14
{
15
16
    abstract protected function aggregateNumericData(
17
        array $dataList,
18
        ScalarValueInterface ...$elements
19
    ): ?ValueInterface;
20
21
    final public function tryAggregate(ValueInterface $value): ?ValueInterface
22
    {
23
        $numericElements = $this->findNumericElements($value);
24
        if (empty($numericElements)) {
25
            return null;
26
        }
27
28
        return $this->aggregateNumericData(
29
            $this->getElementDataList(...$numericElements),
30
            ...$numericElements
31
        );
32
    }
33
34
    protected function findNumericElement(ValueInterface $element): ?ScalarValueInterface
35
    {
36
        if (!$element instanceof ScalarValueInterface) {
37
            return null;
38
        }
39
        $elementData = $element->getData();
40
        return is_int($elementData) || is_float($elementData)
41
            ? $element
42
            : null;
43
    }
44
45
    /**
46
     * @param ValueInterface $value
47
     * @return ScalarValueInterface[]
48
     */
49
    protected function findNumericElements(ValueInterface $value): array
50
    {
51
        $numericElements = [];
52
        if (!$value instanceof ArrayValueInterface) {
53
            return $numericElements;
54
        }
55
        foreach ($value->createChildIterator() as $element) {
56
            $numericElement = $this->findNumericElement($element);
57
            if (isset($numericElement)) {
58
                $numericElements[] = $numericElement;
59
            }
60
        }
61
        return $numericElements;
62
    }
63
64
    protected function getElementDataList(ScalarValueInterface ...$elements): array
65
    {
66
        return array_map([$this, 'getElementData'], $elements);
67
    }
68
69
    private function getElementData(ScalarValueInterface $element)
70
    {
71
        return $element->getData();
72
    }
73
}
74