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

TaskListItemMarkerParser   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
eloc 14
c 0
b 0
f 0
dl 0
loc 32
ccs 15
cts 15
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getMatchDefinition() 0 3 1
A parse() 0 25 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