Completed
Push — master ( 040f68...6483aa )
by Colin
14s queued 10s
created

BacktickParser::parse()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 8.0069

Importance

Changes 0
Metric Value
dl 0
loc 39
ccs 20
cts 21
cp 0.9524
rs 8.0515
c 0
b 0
f 0
cc 8
nc 5
nop 1
crap 8.0069
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\Inline\Parser;
16
17
use League\CommonMark\Inline\Element\Code;
18
use League\CommonMark\Inline\Element\Text;
19
use League\CommonMark\InlineParserContext;
20
21
final class BacktickParser implements InlineParserInterface
22
{
23
    /**
24
     * @return string[]
25
     */
26 2064
    public function getCharacters(): array
27
    {
28 2064
        return ['`'];
29
    }
30
31
    /**
32
     * @param InlineParserContext $inlineContext
33
     *
34
     * @return bool
35
     */
36 147
    public function parse(InlineParserContext $inlineContext): bool
37
    {
38 147
        $cursor = $inlineContext->getCursor();
39
40 147
        $ticks = $cursor->match('/^`+/');
41 147
        if ($ticks === '') {
42
            return false;
43
        }
44
45 147
        $currentPosition = $cursor->getPosition();
46 147
        $previousState = $cursor->saveState();
47
48 147
        while ($matchingTicks = $cursor->match('/`+/m')) {
49 114
            if ($matchingTicks === $ticks) {
50 111
                $code = $cursor->getSubstring($currentPosition, $cursor->getPosition() - $currentPosition - \strlen($ticks));
51
52 111
                $c = \preg_replace('/\n/m', ' ', $code);
53
54
                if (
55 111
                    !empty($c) &&
56 111
                    \substr($c, 0, 1) === ' ' &&
57 111
                    \substr($c, -1, 1) === ' ' &&
58 111
                    \preg_match('/[^ ]/', $c)
59
                ) {
60 33
                    $c = \substr($c, 1, -1);
61
                }
62
63 111
                $inlineContext->getContainer()->appendChild(new Code($c));
64
65 111
                return true;
66
            }
67
        }
68
69
        // If we got here, we didn't match a closing backtick sequence
70 51
        $cursor->restoreState($previousState);
71 51
        $inlineContext->getContainer()->appendChild(new Text($ticks));
72
73 51
        return true;
74
    }
75
}
76