RelativeNormalizerStrategy   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 7
eloc 22
c 1
b 0
f 1
dl 0
loc 52
ccs 21
cts 21
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A addItem() 0 31 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\TableOfContents\Normalizer;
15
16
use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock;
17
use League\CommonMark\Extension\CommonMark\Node\Block\ListItem;
18
use League\CommonMark\Extension\TableOfContents\Node\TableOfContents;
19
20
final class RelativeNormalizerStrategy implements NormalizerStrategyInterface
21
{
22
    /**
23
     * @var TableOfContents
24
     *
25
     * @psalm-readonly
26
     */
27
    private $toc;
28
29
    /**
30
     * @var array<int, ListItem>
31
     *
32
     * @psalm-readonly-allow-private-mutation
33
     */
34
    private $listItemStack = [];
35
36 36
    public function __construct(TableOfContents $toc)
37
    {
38 36
        $this->toc = $toc;
39 36
    }
40
41 33
    public function addItem(int $level, ListItem $listItemToAdd): void
42
    {
43 33
        \end($this->listItemStack);
44 33
        $previousLevel = \key($this->listItemStack);
45
46
        // Pop the stack if we're too deep
47 33
        while ($previousLevel !== null && $level < $previousLevel) {
48 12
            \array_pop($this->listItemStack);
49 12
            \end($this->listItemStack);
50 12
            $previousLevel = \key($this->listItemStack);
51
        }
52
53 33
        $lastListItem = \current($this->listItemStack);
54
55
        // Need to go one level deeper? Add that level
56 33
        if ($lastListItem !== false && $level > $previousLevel) {
57 30
            $targetListBlock = new ListBlock($lastListItem->getListData());
58 30
            $targetListBlock->setStartLine($listItemToAdd->getStartLine());
59 30
            $targetListBlock->setEndLine($listItemToAdd->getEndLine());
60 30
            $lastListItem->appendChild($targetListBlock);
61
        // Otherwise we're at the right level
62
        // If there's no stack we're adding this item directly to the TOC element
63 33
        } elseif ($lastListItem === false) {
64 33
            $targetListBlock = $this->toc;
65
        // Otherwise add it to the last list item
66
        } else {
67 18
            $targetListBlock = $lastListItem->parent();
68
        }
69
70 33
        $targetListBlock->appendChild($listItemToAdd);
71 33
        $this->listItemStack[$level] = $listItemToAdd;
72 33
    }
73
}
74