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
|
2427 |
|
public function getCharacters(): array |
27
|
|
|
{ |
28
|
2427 |
|
return ['`']; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param InlineParserContext $inlineContext |
33
|
|
|
* |
34
|
|
|
* @return bool |
35
|
|
|
*/ |
36
|
168 |
|
public function parse(InlineParserContext $inlineContext): bool |
37
|
|
|
{ |
38
|
168 |
|
$cursor = $inlineContext->getCursor(); |
39
|
|
|
|
40
|
168 |
|
$ticks = $cursor->match('/^`+/'); |
41
|
|
|
|
42
|
168 |
|
$currentPosition = $cursor->getPosition(); |
43
|
168 |
|
$previousState = $cursor->saveState(); |
44
|
|
|
|
45
|
168 |
|
while ($matchingTicks = $cursor->match('/`+/m')) { |
46
|
132 |
|
if ($matchingTicks === $ticks) { |
47
|
129 |
|
$code = $cursor->getSubstring($currentPosition, $cursor->getPosition() - $currentPosition - \strlen($ticks)); |
48
|
|
|
|
49
|
129 |
|
$c = \preg_replace('/\n/m', ' ', $code); |
50
|
|
|
|
51
|
|
|
if ( |
52
|
129 |
|
!empty($c) && |
53
|
129 |
|
$c[0] === ' ' && |
54
|
129 |
|
\substr($c, -1, 1) === ' ' && |
55
|
129 |
|
\preg_match('/[^ ]/', $c) |
56
|
|
|
) { |
57
|
33 |
|
$c = \substr($c, 1, -1); |
58
|
|
|
} |
59
|
|
|
|
60
|
129 |
|
$inlineContext->getContainer()->appendChild(new Code($c)); |
61
|
|
|
|
62
|
129 |
|
return true; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
// If we got here, we didn't match a closing backtick sequence |
67
|
57 |
|
$cursor->restoreState($previousState); |
68
|
57 |
|
$inlineContext->getContainer()->appendChild(new Text($ticks)); |
69
|
|
|
|
70
|
57 |
|
return true; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|