BacktickParser   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 95%

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 5
dl 0
loc 49
ccs 19
cts 20
cp 0.95
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getCharacters() 0 4 1
B parse() 0 33 8
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 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 = \mb_substr($cursor->getLine(), $currentPosition, $cursor->getPosition() - $currentPosition - \strlen($ticks), 'utf-8');
51 111
                $c = \preg_replace('/\n/m', ' ', $code);
52
53 111
                if ($c !== '' && \preg_match('/[^ ]/', $c) && \mb_substr($c, 0, 1) === ' ' && \mb_substr($c, -1, 1) === ' ') {
54 33
                    $c = \mb_substr($c, 1, -1);
55
                }
56
57 111
                $inlineContext->getContainer()->appendChild(new Code($c));
58
59 111
                return true;
60
            }
61
        }
62
63
        // If we got here, we didn't match a closing backtick sequence
64 51
        $cursor->restoreState($previousState);
65 51
        $inlineContext->getContainer()->appendChild(new Text($ticks));
66
67 51
        return true;
68
    }
69
}
70