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

NumericAggregator   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 59
ccs 0
cts 27
cp 0
rs 10
c 0
b 0
f 0
wmc 12

5 Methods

Rating   Name   Duplication   Size   Complexity  
A tryAggregate() 0 10 2
A findNumericElement() 0 9 4
A findNumericElements() 0 13 4
A getElementDataList() 0 3 1
A getElementData() 0 3 1
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