Completed
Push — master ( 0b0b24...54ff37 )
by Colin
02:37
created

BacktickParser::parse()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 19
cts 19
cp 1
rs 8.4106
c 0
b 0
f 0
cc 7
nc 4
nop 1
crap 7
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
7
 *
8
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
9
 *  - (c) John MacFarlane
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace League\CommonMark\Extension\CommonMark\Parser\Inline;
16
17
use League\CommonMark\Extension\CommonMark\Node\Inline\Code;
18
use League\CommonMark\Node\Inline\Text;
19
use League\CommonMark\Parser\Inline\InlineParserInterface;
20
use League\CommonMark\Parser\InlineParserContext;
21
22
final class BacktickParser implements InlineParserInterface
23
{
24 2490
    public function getCharacters(): array
25
    {
26 2490
        return ['`'];
27
    }
28
29 168
    public function parse(InlineParserContext $inlineContext): bool
30
    {
31 168
        $cursor = $inlineContext->getCursor();
32
33 168
        $ticks = $cursor->match('/^`+/');
34
35 168
        $currentPosition = $cursor->getPosition();
36 168
        $previousState = $cursor->saveState();
37
38 168
        while ($matchingTicks = $cursor->match('/`+/m')) {
39 132
            if ($matchingTicks === $ticks) {
40 129
                $code = $cursor->getSubstring($currentPosition, $cursor->getPosition() - $currentPosition - \strlen($ticks));
41
42 129
                $c = \preg_replace('/\n/m', ' ', $code);
43
44
                if (
45 129
                    !empty($c) &&
46 129
                    $c[0] === ' ' &&
47 129
                    \substr($c, -1, 1) === ' ' &&
48 129
                    \preg_match('/[^ ]/', $c)
49
                ) {
50 33
                    $c = \substr($c, 1, -1);
51
                }
52
53 129
                $inlineContext->getContainer()->appendChild(new Code($c));
54
55 129
                return true;
56
            }
57
        }
58
59
        // If we got here, we didn't match a closing backtick sequence
60 57
        $cursor->restoreState($previousState);
61 57
        $inlineContext->getContainer()->appendChild(new Text($ticks));
62
63 57
        return true;
64
    }
65
}
66