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

NodeValueListBuilder::valueExists()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 2
dl 0
loc 15
ccs 9
cts 9
cp 1
crap 4
rs 10
c 0
b 0
f 0
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