1<?php
2
3/*
4 * This file is part of the league/commonmark package.
5 *
6 * (c) Colin O'Dell <colinodell@gmail.com>
7 *
8 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
9 *  - (c) John MacFarlane
10 *
11 * For the full copyright and license information, please view the LICENSE
12 * file that was distributed with this source code.
13 */
14
15namespace League\CommonMark\Reference;
16
17use League\CommonMark\Normalizer\TextNormalizer;
18
19/**
20 * A collection of references, indexed by label
21 */
22final class ReferenceMap implements ReferenceMapInterface
23{
24    /** @var TextNormalizer */
25    private $normalizer;
26
27    /**
28     * @var ReferenceInterface[]
29     */
30    private $references = [];
31
32    public function __construct()
33    {
34        $this->normalizer = new TextNormalizer();
35    }
36
37    public function addReference(ReferenceInterface $reference): void
38    {
39        $key = $this->normalizer->normalize($reference->getLabel());
40
41        $this->references[$key] = $reference;
42    }
43
44    public function contains(string $label): bool
45    {
46        $label = $this->normalizer->normalize($label);
47
48        return isset($this->references[$label]);
49    }
50
51    public function getReference(string $label): ?ReferenceInterface
52    {
53        $label = $this->normalizer->normalize($label);
54
55        if (!isset($this->references[$label])) {
56            return null;
57        }
58
59        return $this->references[$label];
60    }
61
62    public function listReferences(): iterable
63    {
64        return \array_values($this->references);
65    }
66}
67