Completed
Push — latest ( 609def...dcbb7e )
by Colin
14s queued 11s
created

AnonymousFootnoteRefParser::parse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
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
13
declare(strict_types=1);
14
15
namespace League\CommonMark\Extension\Footnote\Parser;
16
17
use League\CommonMark\Configuration\ConfigurationAwareInterface;
18
use League\CommonMark\Configuration\ConfigurationInterface;
19
use League\CommonMark\Extension\Footnote\Node\FootnoteRef;
20
use League\CommonMark\Normalizer\SlugNormalizer;
21
use League\CommonMark\Normalizer\TextNormalizerInterface;
22
use League\CommonMark\Parser\Inline\InlineParserInterface;
23
use League\CommonMark\Parser\Inline\InlineParserMatch;
24
use League\CommonMark\Parser\InlineParserContext;
25
use League\CommonMark\Reference\Reference;
26
27
final class AnonymousFootnoteRefParser implements InlineParserInterface, ConfigurationAwareInterface
28
{
29
    /** @var ConfigurationInterface */
30
    private $config;
31
32
    /**
33
     * @var TextNormalizerInterface
34
     *
35
     * @psalm-readonly
36
     */
37
    private $slugNormalizer;
38
39 105
    public function __construct()
40
    {
41 105
        $this->slugNormalizer = new SlugNormalizer();
42 105
    }
43
44 105
    public function getMatchDefinition(): InlineParserMatch
45
    {
46 105
        return InlineParserMatch::regex('\^\[([^\]]+)\]');
47
    }
48
49 21
    public function parse(InlineParserContext $inlineContext): bool
50
    {
51 21
        $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength());
52
53 21
        [$label]   = $inlineContext->getSubMatches();
54 21
        $reference = $this->createReference($label);
55 21
        $inlineContext->getContainer()->appendChild(new FootnoteRef($reference, $label));
56
57 21
        return true;
58
    }
59
60
    /**
61
     * @psalm-immutable
62
     */
63 21
    private function createReference(string $label): Reference
64
    {
65 21
        $refLabel = $this->slugNormalizer->normalize($label);
66 21
        $refLabel = \mb_substr($refLabel, 0, 20);
67
68 21
        return new Reference(
69 14
            $refLabel,
70 21
            '#' . $this->config->get('footnote/footnote_id_prefix', 'fn:') . $refLabel,
71 7
            $label
72
        );
73
    }
74
75 105
    public function setConfiguration(ConfigurationInterface $config): void
76
    {
77 105
        $this->config = $config;
78 105
    }
79
}
80