Completed
Push — master ( 52e853...8255d7 )
by Colin
01:03
created

RelativeNormalizerStrategy::addItem()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 31
c 0
b 0
f 0
ccs 17
cts 17
cp 1
rs 8.8017
cc 6
nc 6
nop 2
crap 6
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\TableOfContents\Normalizer;
13
14
use League\CommonMark\Block\Element\ListBlock;
15
use League\CommonMark\Block\Element\ListItem;
16
use League\CommonMark\Extension\TableOfContents\TableOfContents;
17
18
final class RelativeNormalizerStrategy implements NormalizerStrategyInterface
19
{
20
    /** @var TableOfContents */
21
    private $toc;
22
23
    /** @var array<int, ListItem> */
24
    private $listItemStack = [];
25
26 27
    public function __construct(TableOfContents $toc)
27
    {
28 27
        $this->toc = $toc;
29 27
    }
30
31 24
    public function addItem(int $level, ListItem $listItemToAdd)
32
    {
33 24
        \end($this->listItemStack);
34 24
        $previousLevel = \key($this->listItemStack);
35
36
        // Pop the stack if we're too deep
37 24
        while ($previousLevel !== null && $level < $previousLevel) {
38 12
            array_pop($this->listItemStack);
39 12
            \end($this->listItemStack);
40 12
            $previousLevel = \key($this->listItemStack);
41
        }
42
43
        /** @var ListItem|false $lastListItem */
44 24
        $lastListItem = \current($this->listItemStack);
45
46
        // Need to go one level deeper? Add that level
47 24
        if ($lastListItem !== false && $level > $previousLevel) {
48 24
            $targetListBlock = new ListBlock($lastListItem->getListData());
49 24
            $lastListItem->appendChild($targetListBlock);
50
        // Otherwise we're at the right level
51
        // If there's no stack we're adding this item directly to the TOC element
52 24
        } elseif ($lastListItem === false) {
53 24
            $targetListBlock = $this->toc;
54
        // Otherwise add it to the last list item
55
        } else {
56 12
            $targetListBlock = $lastListItem->parent();
57
        }
58
59 24
        $targetListBlock->appendChild($listItemToAdd);
60 24
        $this->listItemStack[$level] = $listItemToAdd;
61 24
    }
62
}
63