Completed
Push — master ( 0acfd1...8c96cb )
by Edward
08:27
created

LiteralFactory::createArray()   A

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