Completed
Pull Request — master (#18)
by Elan
02:44
created

StrikeThroughParser::getCharacters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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