Passed
Push — master ( fb6180...9ae624 )
by Edward
03:35
created

LocatorBuilder::export()   A

Complexity

Conditions 2
Paths 2

Size

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