BacktickParser::parse()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 37
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 7

Importance

Changes 0
Metric Value
eloc 21
c 0
b 0
f 0
dl 0
loc 37
ccs 21
cts 21
cp 1
rs 8.6506
cc 7
nc 4
nop 1
crap 7
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\Inline\InlineParserMatch;
23
use League\CommonMark\Parser\InlineParserContext;
24
25
final class BacktickParser implements InlineParserInterface
26
{
27 2982
    public function getMatchDefinition(): InlineParserMatch
28
    {
29 2982
        return InlineParserMatch::regex('`+');
30
    }
31
32 156
    public function parse(InlineParserContext $inlineContext): bool
33
    {
34 156
        $ticks  = $inlineContext->getFullMatch();
35 156
        $cursor = $inlineContext->getCursor();
36 156
        $cursor->advanceBy($inlineContext->getFullMatchLength());
37
38 156
        $currentPosition = $cursor->getPosition();
39 156
        $previousState   = $cursor->saveState();
40
41 156
        while ($matchingTicks = $cursor->match('/`+/m')) {
42 135
            if ($matchingTicks !== $ticks) {
43 24
                continue;
44
            }
45
46 132
            $code = $cursor->getSubstring($currentPosition, $cursor->getPosition() - $currentPosition - \strlen($ticks));
47
48 132
            $c = \preg_replace('/\n/m', ' ', $code) ?? '';
49
50
            if (
51 132
                $c !== '' &&
52 132
                $c[0] === ' ' &&
53 132
                \substr($c, -1, 1) === ' ' &&
54 132
                \preg_match('/[^ ]/', $c)
55
            ) {
56 27
                $c = \substr($c, 1, -1);
57
            }
58
59 132
            $inlineContext->getContainer()->appendChild(new Code($c));
60
61 132
            return true;
62
        }
63
64
        // If we got here, we didn't match a closing backtick sequence
65 42
        $cursor->restoreState($previousState);
66 42
        $inlineContext->getContainer()->appendChild(new Text($ticks));
67
68 42
        return true;
69
    }
70
}
71