BacktickParser   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 95.83%

Importance

Changes 0
Metric Value
wmc 9
eloc 24
dl 0
loc 49
ccs 23
cts 24
cp 0.9583
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getCharacters() 0 3 1
B parse() 0 39 8
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the league/commonmark package.
7
 *
8
 * (c) Colin O'Dell <[email protected]>
9
 *
10
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
11
 *  - (c) John MacFarlane
12
 *
13
 * For the full copyright and license information, please view the LICENSE
14
 * file that was distributed with this source code.
15
 */
16
17
namespace League\CommonMark\Extension\CommonMark\Parser\Inline;
18
19
use League\CommonMark\Extension\CommonMark\Node\Inline\Code;
20
use League\CommonMark\Node\Inline\Text;
21
use League\CommonMark\Parser\Inline\InlineParserInterface;
22
use League\CommonMark\Parser\InlineParserContext;
23
24
final class BacktickParser implements InlineParserInterface
25
{
26
    /**
27
     * {@inheritdoc}
28
     */
29 2880
    public function getCharacters(): array
30
    {
31 2880
        return ['`'];
32
    }
33
34 150
    public function parse(InlineParserContext $inlineContext): bool
35
    {
36 150
        $cursor = $inlineContext->getCursor();
37 150
        $ticks  = $cursor->match('/^`+/');
38 150
        if ($ticks === null) {
39
            return false; // This should never happen
40
        }
41
42 150
        $currentPosition = $cursor->getPosition();
43 150
        $previousState   = $cursor->saveState();
44
45 150
        while ($matchingTicks = $cursor->match('/`+/m')) {
46 129
            if ($matchingTicks !== $ticks) {
47 24
                continue;
48
            }
49
50 126
            $code = $cursor->getSubstring($currentPosition, $cursor->getPosition() - $currentPosition - \strlen($ticks));
51
52 126
            $c = \preg_replace('/\n/m', ' ', $code) ?? '';
53
54
            if (
55 126
                $c !== '' &&
56 126
                $c[0] === ' ' &&
57 126
                \substr($c, -1, 1) === ' ' &&
58 126
                \preg_match('/[^ ]/', $c)
59
            ) {
60 27
                $c = \substr($c, 1, -1);
61
            }
62
63 126
            $inlineContext->getContainer()->appendChild(new Code($c));
64
65 126
            return true;
66
        }
67
68
        // If we got here, we didn't match a closing backtick sequence
69 42
        $cursor->restoreState($previousState);
70 42
        $inlineContext->getContainer()->appendChild(new Text($ticks));
71
72 42
        return true;
73
    }
74
}
75