Completed
Push — master ( b42489...8df37e )
by Colin
14s queued 11s
created

BacktickParser   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 92%

Importance

Changes 0
Metric Value
wmc 10
lcom 0
cbo 5
dl 0
loc 59
ccs 23
cts 25
cp 0.92
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getCharacters() 0 4 1
B parse() 0 43 9
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 2070
    public function getCharacters(): array
27
    {
28 2070
        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
        if ($cursor->getCharacter() !== '`') {
41
            return false;
42
        }
43
44 147
        $ticks = $cursor->match('/^`+/');
45 147
        if ($ticks === '') {
46
            return false;
47
        }
48
49 147
        $currentPosition = $cursor->getPosition();
50 147
        $previousState = $cursor->saveState();
51
52 147
        while ($matchingTicks = $cursor->match('/`+/m')) {
53 114
            if ($matchingTicks === $ticks) {
54 111
                $code = $cursor->getSubstring($currentPosition, $cursor->getPosition() - $currentPosition - \strlen($ticks));
55
56 111
                $c = \preg_replace('/\n/m', ' ', $code);
57
58
                if (
59 111
                    !empty($c) &&
60 111
                    $c[0] === ' ' &&
61 111
                    \substr($c, -1, 1) === ' ' &&
62 111
                    \preg_match('/[^ ]/', $c)
63
                ) {
64 33
                    $c = \substr($c, 1, -1);
65
                }
66
67 111
                $inlineContext->getContainer()->appendChild(new Code($c));
68
69 111
                return true;
70
            }
71
        }
72
73
        // If we got here, we didn't match a closing backtick sequence
74 51
        $cursor->restoreState($previousState);
75 51
        $inlineContext->getContainer()->appendChild(new Text($ticks));
76
77 51
        return true;
78
    }
79
}
80