Passed
Push — master ( a2958a...1131f0 )
by Edward
02:35
created

LiteralArrayValueList::createValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Remorhaz\JSON\Path\Value;
5
6
use function array_fill_keys;
7
use function array_map;
8
use Remorhaz\JSON\Data\Value\ValueInterface;
9
10
final class LiteralArrayValueList implements ValueListInterface
11
{
12
13
    private $indexMap;
14
15
    private $values;
16
17
    private $valueLists;
18
19
    public function __construct(IndexMapInterface $indexMap, ValueListInterface ...$valueLists)
20
    {
21
        $this->indexMap = $indexMap;
22
        foreach ($valueLists as $valueList) {
23
            if (!$this->indexMap->equals($valueList->getIndexMap())) {
24
                throw new Exception\IndexMapMatchFailedException($valueList, $this);
25
            }
26
        }
27
        $this->valueLists = $valueLists;
28
    }
29
30
    public function getIndexMap(): IndexMapInterface
31
    {
32
        return $this->indexMap;
33
    }
34
35
    public function getValues(): array
36
    {
37
        if (!isset($this->values)) {
38
            $this->values = $this->loadValues();
39
        }
40
41
        return $this->values;
42
    }
43
44
    private function loadValues(): array
45
    {
46
        $elementLists = array_fill_keys($this->indexMap->getInnerIndice(), []);
47
        foreach ($this->valueLists as $valueList) {
48
            foreach ($valueList->getValues() as $innerIndex => $value) {
49
                $elementLists[$innerIndex][] = $value;
50
            }
51
        }
52
53
        return array_map([$this, 'createValue'], $elementLists);
54
    }
55
56
    private function createValue(array $elements): ValueInterface
57
    {
58
        return new LiteralArrayValue($this->indexMap, ...$elements);
59
    }
60
61
    public function getValue(int $index): ValueInterface
62
    {
63
        $values = $this->getValues();
64
        if (!isset($values[$index])) {
65
            throw new Exception\ValueNotFoundException($index, $this);
66
        }
67
68
        return $values[$index];
69
    }
70
}
71