Passed
Push — latest ( 212a66...171a44 )
by Colin
01:50
created

AnonymousFootnoteRefParser   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 21
c 1
b 0
f 0
dl 0
loc 57
ccs 22
cts 24
cp 0.9167
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getCharacters() 0 3 1
A createReference() 0 6 1
A __construct() 0 3 1
A parse() 0 24 4
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\Extension\Footnote\Node\FootnoteRef;
18
use League\CommonMark\Normalizer\SlugNormalizer;
19
use League\CommonMark\Normalizer\TextNormalizerInterface;
20
use League\CommonMark\Parser\Inline\InlineParserInterface;
21
use League\CommonMark\Parser\InlineParserContext;
22
use League\CommonMark\Reference\Reference;
23
24
final class AnonymousFootnoteRefParser implements InlineParserInterface
25
{
26
    /**
27
     * @var TextNormalizerInterface
28
     *
29
     * @psalm-readonly
30
     */
31
    private $slugNormalizer;
32
33 90
    public function __construct()
34
    {
35 90
        $this->slugNormalizer = new SlugNormalizer();
36 90
    }
37
38
    /**
39
     * {@inheritDoc}
40
     */
41 90
    public function getCharacters(): array
42
    {
43 90
        return ['^'];
44
    }
45
46 27
    public function parse(InlineParserContext $inlineContext): bool
47
    {
48 27
        $container = $inlineContext->getContainer();
49 27
        $cursor    = $inlineContext->getCursor();
50 27
        $nextChar  = $cursor->peek();
51 27
        if ($nextChar !== '[') {
52 6
            return false;
53
        }
54
55 21
        $state = $cursor->saveState();
56
57 21
        $m = $cursor->match('#\^\[[^\]]+\]#');
58 21
        if ($m !== null) {
59 21
            if (\preg_match('#\^\[([^\]]+)\]#', $m, $matches) > 0) {
60 21
                $reference = $this->createReference($matches[1]);
61 21
                $container->appendChild(new FootnoteRef($reference, $matches[1]));
62
63 21
                return true;
64
            }
65
        }
66
67
        $cursor->restoreState($state);
68
69
        return false;
70
    }
71
72
    /**
73
     * @psalm-pure
74
     */
75 21
    private function createReference(string $label): Reference
76
    {
77 21
        $refLabel = $this->slugNormalizer->normalize($label);
78 21
        $refLabel = \mb_substr($refLabel, 0, 20);
79
80 21
        return new Reference($refLabel, '#fn:' . $refLabel, $label);
81
    }
82
}
83