LocatorBuilder::addReference()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Remorhaz\JSON\Pointer\Locator;
6
7
use function array_map;
8
use function implode;
9
use function str_replace;
10
11
final class LocatorBuilder implements LocatorBuilderInterface
12
{
13
14
    private $locator;
15
16
    private $referenceFactory;
17
18
    private $references = [];
19
20 1
    public static function create(): LocatorBuilderInterface
21
    {
22 1
        return new self(new ReferenceFactory());
23
    }
24
25 14
    public function __construct(ReferenceFactoryInterface $referenceFactory)
26
    {
27 14
        $this->referenceFactory = $referenceFactory;
28 14
    }
29
30 10
    public function addReference(string $text): void
31
    {
32 10
        if (isset($this->locator)) {
33 2
            throw new Exception\LocatorAlreadyBuiltException();
34
        }
35
36
        $reference = $this
37 8
            ->referenceFactory
38 8
            ->createReference($text);
39 8
        $this->references[] = $reference;
40 8
    }
41
42 12
    public function getLocator(): LocatorInterface
43
    {
44 12
        if (!isset($this->locator)) {
45 12
            $this->locator = new Locator(...$this->references);
46
        }
47
48 12
        return $this->locator;
49
    }
50
51 8
    public function export(): string
52
    {
53
        $references = $this
54 8
            ->getLocator()
55 8
            ->references();
56
57 8
        if (empty($references)) {
58 2
            return '';
59
        }
60
61 6
        return '/' . implode('/', array_map([$this, 'escapeReference'], $references));
62
    }
63
64 6
    private function escapeReference(ListedReferenceInterface $reference): string
65
    {
66
        $text = $reference
67 6
            ->getReference()
68 6
            ->getPropertyName();
69
70 6
        return str_replace(['~', '/'], ['~0', '~1'], $text);
71
    }
72
}
73