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\Inline\Parser\InlineParserInterface;
19use League\CommonMark\InlineParserContext;
20use League\CommonMark\Reference\Reference;
21use League\CommonMark\Util\ConfigurationAwareInterface;
22use League\CommonMark\Util\ConfigurationInterface;
23
24final class FootnoteRefParser implements InlineParserInterface, ConfigurationAwareInterface
25{
26    /** @var ConfigurationInterface */
27    private $config;
28
29    public function getCharacters(): array
30    {
31        return ['['];
32    }
33
34    public function parse(InlineParserContext $inlineContext): bool
35    {
36        $container = $inlineContext->getContainer();
37        $cursor = $inlineContext->getCursor();
38        $nextChar = $cursor->peek();
39        if ($nextChar !== '^') {
40            return false;
41        }
42
43        $state = $cursor->saveState();
44
45        $m = $cursor->match('#\[\^([^\]]+)\]#');
46        if ($m !== null) {
47            if (\preg_match('#\[\^([^\]]+)\]#', $m, $matches) > 0) {
48                $container->appendChild(new FootnoteRef($this->createReference($matches[1])));
49
50                return true;
51            }
52        }
53
54        $cursor->restoreState($state);
55
56        return false;
57    }
58
59    private function createReference(string $label): Reference
60    {
61        return new Reference(
62            $label,
63            '#' . $this->config->get('footnote/footnote_id_prefix', 'fn:') . $label,
64            $label
65        );
66    }
67
68    public function setConfiguration(ConfigurationInterface $config): void
69    {
70        $this->config = $config;
71    }
72}
73