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
|
8 |
|
final public function tryAggregate(ValueInterface $value): ?ValueInterface |
22
|
|
|
{ |
23
|
8 |
|
$numericElements = $this->findNumericElements($value); |
24
|
8 |
|
if (empty($numericElements)) { |
25
|
3 |
|
return null; |
26
|
|
|
} |
27
|
|
|
|
28
|
5 |
|
return $this->aggregateNumericData( |
29
|
5 |
|
$this->getElementDataList(...$numericElements), |
30
|
5 |
|
...$numericElements |
31
|
|
|
); |
32
|
|
|
} |
33
|
|
|
|
34
|
7 |
|
protected function findNumericElement(ValueInterface $element): ?ScalarValueInterface |
35
|
|
|
{ |
36
|
7 |
|
if (!$element instanceof ScalarValueInterface) { |
37
|
1 |
|
return null; |
38
|
|
|
} |
39
|
6 |
|
$elementData = $element->getData(); |
40
|
6 |
|
return is_int($elementData) || is_float($elementData) |
41
|
5 |
|
? $element |
42
|
6 |
|
: null; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param ValueInterface $value |
47
|
|
|
* @return ScalarValueInterface[] |
48
|
|
|
*/ |
49
|
8 |
|
protected function findNumericElements(ValueInterface $value): array |
50
|
|
|
{ |
51
|
8 |
|
$numericElements = []; |
52
|
8 |
|
if (!$value instanceof ArrayValueInterface) { |
53
|
1 |
|
return $numericElements; |
54
|
|
|
} |
55
|
7 |
|
foreach ($value->createChildIterator() as $element) { |
56
|
7 |
|
$numericElement = $this->findNumericElement($element); |
57
|
7 |
|
if (isset($numericElement)) { |
58
|
5 |
|
$numericElements[] = $numericElement; |
59
|
|
|
} |
60
|
|
|
} |
61
|
7 |
|
return $numericElements; |
62
|
|
|
} |
63
|
|
|
|
64
|
5 |
|
protected function getElementDataList(ScalarValueInterface ...$elements): array |
65
|
|
|
{ |
66
|
5 |
|
return array_map([$this, 'getElementData'], $elements); |
67
|
|
|
} |
68
|
|
|
|
69
|
5 |
|
private function getElementData(ScalarValueInterface $element) |
70
|
|
|
{ |
71
|
5 |
|
return $element->getData(); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|