Completed
Push — master ( d6425f...46570e )
by Colin
15s queued 10s
created

BacktickParser::parse()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 8.0109

Importance

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