1<?php 2 3declare(strict_types=1); 4 5/* 6 * This file is part of the league/commonmark package. 7 * 8 * (c) Colin O'Dell <colinodell@gmail.com> 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 17namespace League\CommonMark\Reference; 18 19use League\CommonMark\Normalizer\TextNormalizer; 20 21/** 22 * A collection of references, indexed by label 23 */ 24final 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 public function __construct() 37 { 38 $this->normalizer = new TextNormalizer(); 39 } 40 41 public function add(ReferenceInterface $reference): void 42 { 43 // Normalize the key 44 $key = $this->normalizer->normalize($reference->getLabel()); 45 // Store the reference 46 $this->references[$key] = $reference; 47 } 48 49 public function contains(string $label): bool 50 { 51 $label = $this->normalizer->normalize($label); 52 53 return isset($this->references[$label]); 54 } 55 56 public function get(string $label): ?ReferenceInterface 57 { 58 $label = $this->normalizer->normalize($label); 59 60 return $this->references[$label] ?? null; 61 } 62 63 /** 64 * @return \Traversable<string, ReferenceInterface> 65 */ 66 public function getIterator(): \Traversable 67 { 68 foreach ($this->references as $normalizedLabel => $reference) { 69 yield $normalizedLabel => $reference; 70 } 71 } 72 73 public function count(): int 74 { 75 return \count($this->references); 76 } 77} 78