LiteralFactory::createArray()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 7
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 11
ccs 0
cts 9
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Remorhaz\JSON\Path\Runtime;
6
7
use Remorhaz\JSON\Data\Value\ValueInterface;
8
use Remorhaz\JSON\Path\Value\LiteralArrayValue;
9
use Remorhaz\JSON\Path\Value\LiteralScalarValue;
10
use Remorhaz\JSON\Path\Value\LiteralValueList;
11
use Remorhaz\JSON\Path\Value\NodeValueListInterface;
12
use Remorhaz\JSON\Path\Value\ValueList;
13
use Remorhaz\JSON\Path\Value\ValueListInterface;
14
15
class LiteralFactory implements LiteralFactoryInterface
16
{
17
18
    public function createScalar(NodeValueListInterface $source, $value): ValueListInterface
19
    {
20
        return new LiteralValueList($source->getIndexMap(), new LiteralScalarValue($value));
21
    }
22
23
    public function createArray(NodeValueListInterface $source, ValueListInterface ...$valueLists): ValueListInterface
24
    {
25
        $createArrayElement = function (array $elements): ValueInterface {
26
            return new LiteralArrayValue(...$elements);
27
        };
28
29
        return new ValueList(
30
            $source->getIndexMap(),
31
            ...array_map(
32
                $createArrayElement,
33
                $this->buildArrayElementLists($source, ...$valueLists)
34
            )
35
        );
36
    }
37
38
    private function buildArrayElementLists(NodeValueListInterface $source, ValueListInterface ...$valueLists): array
39
    {
40
        $elementLists = array_fill_keys($source->getIndexMap()->getInnerIndexes(), []);
41
        foreach ($valueLists as $valueList) {
42
            if (!$source->getIndexMap()->equals($valueList->getIndexMap())) {
43
                throw new Exception\IndexMapMatchFailedException($valueList, $source);
44
            }
45
            foreach ($valueList->getValues() as $innerIndex => $value) {
46
                $elementLists[$innerIndex][] = $value;
47
            }
48
        }
49
50
        return $elementLists;
51
    }
52
}
53