Completed
Push — master ( 83739a...a13ee4 )
by Colin
14s queued 11s
created

TaskListItemMarkerParser::parse()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 15
cts 15
cp 1
rs 8.5226
c 0
b 0
f 0
cc 7
nc 4
nop 1
crap 7
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace League\CommonMark\Extension\TaskList;
13
14
use League\CommonMark\Block\Element\ListItem;
15
use League\CommonMark\Block\Element\Paragraph;
16
use League\CommonMark\Inline\Parser\InlineParserInterface;
17
use League\CommonMark\InlineParserContext;
18
19
final class TaskListItemMarkerParser implements InlineParserInterface
20
{
21
    /**
22
     * @return string[]
23
     */
24 75
    public function getCharacters(): array
25
    {
26 75
        return ['['];
27
    }
28
29
    /**
30
     * @param InlineParserContext $inlineContext
31
     *
32
     * @return bool
33
     */
34 9
    public function parse(InlineParserContext $inlineContext): bool
35
    {
36 9
        $container = $inlineContext->getContainer();
37
38
        // Checkbox must come at the beginning of the first paragraph of the list item
39 9
        if ($container->hasChildren() || !($container instanceof Paragraph && $container->parent() && $container->parent() instanceof ListItem)) {
40 3
            return false;
41
        }
42
43 9
        $cursor = $inlineContext->getCursor();
44 9
        $oldState = $cursor->saveState();
45
46 9
        $m = $cursor->match('/\[[ xX]\]/');
47 9
        if ($m === null) {
48 3
            return false;
49
        }
50
51 9
        if ($cursor->getNextNonSpaceCharacter() === null) {
52 3
            $cursor->restoreState($oldState);
53
54 3
            return false;
55
        }
56
57 9
        $isChecked = $m !== '[ ]';
58
59 9
        $container->appendChild(new TaskListItemMarker($isChecked));
60
61 9
        return true;
62
    }
63
}
64