Completed
Push — master ( 6894d9...a74f91 )
by Colin
02:02
created

TaskListItemMarkerParser   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 5
dl 0
loc 45
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getCharacters() 0 4 1
B parse() 0 29 7
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark-ext-task-list 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\Ext\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 3
    public function getCharacters(): array
25
    {
26 3
        return ['['];
27
    }
28
29
    /**
30
     * @param InlineParserContext $inlineContext
31
     *
32
     * @return bool
33
     */
34 3
    public function parse(InlineParserContext $inlineContext): bool
35
    {
36 3
        $container = $inlineContext->getContainer();
37
38
        // Checkbox must come at the beginning of the first paragraph of the list item
39 3
        if ($container->hasChildren() || !($container instanceof Paragraph && $container->parent() && $container->parent() instanceof ListItem)) {
40 3
            return false;
41
        }
42
43 3
        $cursor = $inlineContext->getCursor();
44 3
        $oldState = $cursor->saveState();
45
46 3
        $m = $cursor->match('/\[( |x)\]/i');
47 3
        if ($m === null) {
48 3
            return false;
49
        }
50
51 3
        if ($cursor->getNextNonSpaceCharacter() === null) {
52 3
            $cursor->restoreState($oldState);
53
54 3
            return false;
55
        }
56
57 3
        $isChecked = $m !== '[ ]';
58
59 3
        $inlineContext->getContainer()->appendChild(new TaskListItemMarker($isChecked));
60
61 3
        return true;
62
    }
63
}
64