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\Extension\CommonMark\Node\Block\ListBlock; |
15
|
|
|
use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; |
16
|
|
|
use League\CommonMark\Extension\TableOfContents\Node\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
|
30 |
|
public function __construct(TableOfContents $toc) |
27
|
|
|
{ |
28
|
30 |
|
$this->toc = $toc; |
29
|
30 |
|
} |
30
|
|
|
|
31
|
27 |
|
public function addItem(int $level, ListItem $listItemToAdd): void |
32
|
|
|
{ |
33
|
27 |
|
\end($this->listItemStack); |
34
|
27 |
|
$previousLevel = \key($this->listItemStack); |
35
|
|
|
|
36
|
|
|
// Pop the stack if we're too deep |
37
|
27 |
|
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
|
27 |
|
$lastListItem = \current($this->listItemStack); |
45
|
|
|
|
46
|
|
|
// Need to go one level deeper? Add that level |
47
|
27 |
|
if ($lastListItem !== false && $level > $previousLevel) { |
48
|
27 |
|
$targetListBlock = new ListBlock($lastListItem->getListData()); |
49
|
27 |
|
$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
|
27 |
|
} elseif ($lastListItem === false) { |
53
|
27 |
|
$targetListBlock = $this->toc; |
54
|
|
|
// Otherwise add it to the last list item |
55
|
|
|
} else { |
56
|
15 |
|
$targetListBlock = $lastListItem->parent(); |
57
|
|
|
} |
58
|
|
|
|
59
|
27 |
|
$targetListBlock->appendChild($listItemToAdd); |
60
|
27 |
|
$this->listItemStack[$level] = $listItemToAdd; |
61
|
27 |
|
} |
62
|
|
|
} |
63
|
|
|
|