Passed
Push — master ( 511e20...91b368 )
by Edward
08:33 queued 05:58
created

NodeValueListBuilder::build()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 1
b 0
f 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Remorhaz\JSON\Path\Value;
6
7
use Remorhaz\JSON\Data\Value\NodeValueInterface;
8
9
final class NodeValueListBuilder
10
{
11
12
    private $outerIndexes = [];
13
14
    /**
15
     * @var NodeValueInterface[]
16
     */
17
    private $values = [];
18
19 7
    public function addValue(NodeValueInterface $value, int $outerIndex): self
20
    {
21 7
        if ($this->valueExists($value, $outerIndex)) {
22 1
            return $this;
23
        }
24
25 7
        $this->outerIndexes[] = $outerIndex;
26 7
        $this->values[] = $value;
27
28 7
        return $this;
29
    }
30
31 7
    public function build(): NodeValueListInterface
32
    {
33 7
        return new NodeValueList(new IndexMap(...$this->outerIndexes), ...$this->values);
34
    }
35
36 7
    private function valueExists(NodeValueInterface $value, int $outerIndex): bool
37
    {
38 7
        foreach ($this->values as $innerIndex => $addedValue) {
39 4
            if (!$addedValue->getPath()->equals($value->getPath())) {
40 2
                continue;
41
            }
42 2
            $addedOuterIndex = $this->outerIndexes[$innerIndex];
43 2
            if ($outerIndex == $addedOuterIndex) {
44 1
                return true;
45
            }
46
47 1
            throw new Exception\ValueInListWithAnotherOuterIndexException($value, $addedOuterIndex, $outerIndex);
48
        }
49
50 7
        return false;
51
    }
52
}
53