Completed
Pull Request — master (#18)
by Elan
06:19
created

StrikeThroughParser::getCharacters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace League\CommonMark\Extras\StrikeThrough;
4
5
use League\CommonMark\Inline\Element\Text;
6
use League\CommonMark\Inline\Parser\AbstractInlineParser;
7
use League\CommonMark\InlineParserContext;
8
9
class StrikeThroughParser extends AbstractInlineParser {
10
    public function getCharacters()
11
    {
12
        return ['~'];
13
    }
14
15
    public function parse(InlineParserContext $inlineContext)
16
    {
17
        $cursor = $inlineContext->getCursor();
18
        $character = $cursor->getCharacter();
19
        if ($cursor->peek(1) != $character) {
20
            return false;
21
        }
22
        $tildes = $cursor->match('/^~~+/');
23
        if ($tildes === '') {
24
            false;
25
        }
26
        $previousState = $cursor->saveState();
27
        $currentPosition = $cursor->getPosition();
28
        while ($matchingTildes = $cursor->match('/~~+/m')) {
29
            if ($matchingTildes === $tildes) {
30
                $text = mb_substr($cursor->getLine(), $currentPosition, $cursor->getPosition() - $currentPosition - strlen($tildes), 'utf-8');
31
                $text = preg_replace('/[ \n]+/', ' ', $text);
32
                $inlineContext->getContainer()->appendChild(new StrikeThroughElement(trim($text)));
33
                return true;
34
            }
35
        }
36
        $cursor->restoreState($previousState);
37
        $inlineContext->getContainer()->appendChild(new Text($tildes));
38
        return false;
39
    }
40
}