ReferenceMap::__construct()   A
last analyzed

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 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the league/commonmark package.
7
 *
8
 * (c) Colin O'Dell <[email protected]>
9
 *
10
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
11
 *  - (c) John MacFarlane
12
 *
13
 * For the full copyright and license information, please view the LICENSE
14
 * file that was distributed with this source code.
15
 */
16
17
namespace League\CommonMark\Reference;
18
19
use League\CommonMark\Normalizer\TextNormalizer;
20
21
/**
22
 * A collection of references, indexed by label
23
 */
24
final class ReferenceMap implements ReferenceMapInterface
25
{
26
    /** @psalm-readonly */
27
    private TextNormalizer $normalizer;
28
29
    /**
30
     * @var array<string, ReferenceInterface>
31
     *
32
     * @psalm-readonly-allow-private-mutation
33
     */
34
    private array $references = [];
35
36 2484
    public function __construct()
37
    {
38 2484
        $this->normalizer = new TextNormalizer();
39
    }
40
41 270
    public function add(ReferenceInterface $reference): void
42
    {
43
        // Normalize the key
44 270
        $key = $this->normalizer->normalize($reference->getLabel());
45
        // Store the reference
46 270
        $this->references[$key] = $reference;
47
    }
48
49 180
    public function contains(string $label): bool
50
    {
51 180
        if ($this->references === []) {
52 168
            return false;
53
        }
54
55 26
        $label = $this->normalizer->normalize($label);
56
57 26
        return isset($this->references[$label]);
58
    }
59
60 312
    public function get(string $label): ?ReferenceInterface
61
    {
62 312
        if ($this->references === []) {
63 78
            return null;
64
        }
65
66 236
        $label = $this->normalizer->normalize($label);
67
68 236
        return $this->references[$label] ?? null;
69
    }
70
71
    /**
72
     * @return \Traversable<string, ReferenceInterface>
73
     */
74 2
    public function getIterator(): \Traversable
75
    {
76 2
        foreach ($this->references as $normalizedLabel => $reference) {
77 2
            yield $normalizedLabel => $reference;
78
        }
79
    }
80
81 4
    public function count(): int
82
    {
83 4
        return \count($this->references);
84
    }
85
}
86