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\Extension\Footnote\Node\FootnoteRef;
18use League\CommonMark\Parser\Inline\InlineParserInterface;
19use League\CommonMark\Parser\Inline\InlineParserMatch;
20use League\CommonMark\Parser\InlineParserContext;
21use League\CommonMark\Reference\Reference;
22use League\Config\ConfigurationAwareInterface;
23use League\Config\ConfigurationInterface;
24
25final class FootnoteRefParser implements InlineParserInterface, ConfigurationAwareInterface
26{
27    private ConfigurationInterface $config;
28
29    public function getMatchDefinition(): InlineParserMatch
30    {
31        return InlineParserMatch::regex('\[\^([^\s\]]+)\]');
32    }
33
34    public function parse(InlineParserContext $inlineContext): bool
35    {
36        $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength());
37
38        [$label] = $inlineContext->getSubMatches();
39        $inlineContext->getContainer()->appendChild(new FootnoteRef($this->createReference($label)));
40
41        return true;
42    }
43
44    private function createReference(string $label): Reference
45    {
46        return new Reference(
47            $label,
48            '#' . $this->config->get('footnote/footnote_id_prefix') . $label,
49            $label
50        );
51    }
52
53    public function setConfiguration(ConfigurationInterface $configuration): void
54    {
55        $this->config = $configuration;
56    }
57}
58