1<?php
2
3/*
4 * This file is part of the league/commonmark package.
5 *
6 * (c) Colin O'Dell <colinodell@gmail.com>
7 * (c) Rezo Zero / Ambroise Maupate
8 *
9 * For the full copyright and license information, please view the LICENSE
10 * file that was distributed with this source code.
11 */
12
13declare(strict_types=1);
14
15namespace League\CommonMark\Extension\Footnote\Parser;
16
17use League\CommonMark\Environment\EnvironmentAwareInterface;
18use League\CommonMark\Environment\EnvironmentInterface;
19use League\CommonMark\Extension\Footnote\Node\FootnoteRef;
20use League\CommonMark\Normalizer\TextNormalizerInterface;
21use League\CommonMark\Parser\Inline\InlineParserInterface;
22use League\CommonMark\Parser\Inline\InlineParserMatch;
23use League\CommonMark\Parser\InlineParserContext;
24use League\CommonMark\Reference\Reference;
25use League\Config\ConfigurationInterface;
26
27final class AnonymousFootnoteRefParser implements InlineParserInterface, EnvironmentAwareInterface
28{
29    private ConfigurationInterface $config;
30
31    /** @psalm-readonly-allow-private-mutation */
32    private TextNormalizerInterface $slugNormalizer;
33
34    public function getMatchDefinition(): InlineParserMatch
35    {
36        return InlineParserMatch::regex('\^\[([^\]]+)\]');
37    }
38
39    public function parse(InlineParserContext $inlineContext): bool
40    {
41        $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength());
42
43        [$label]   = $inlineContext->getSubMatches();
44        $reference = $this->createReference($label);
45        $inlineContext->getContainer()->appendChild(new FootnoteRef($reference, $label));
46
47        return true;
48    }
49
50    private function createReference(string $label): Reference
51    {
52        $refLabel = $this->slugNormalizer->normalize($label, ['length' => 20]);
53
54        return new Reference(
55            $refLabel,
56            '#' . $this->config->get('footnote/footnote_id_prefix') . $refLabel,
57            $label
58        );
59    }
60
61    public function setEnvironment(EnvironmentInterface $environment): void
62    {
63        $this->config         = $environment->getConfiguration();
64        $this->slugNormalizer = $environment->getSlugNormalizer();
65    }
66}
67