Completed
Push — latest ( 76d169...995567 )
by Colin
22s queued 10s
created

TaskListItemMarkerParser::parse()   A

Complexity

Conditions 6
Paths 3

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

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