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 AsIsNormalizerStrategy implements NormalizerStrategyInterface |
19
|
|
|
{ |
20
|
|
|
/** @var ListBlock */ |
21
|
|
|
private $parentListBlock; |
22
|
|
|
/** @var int */ |
23
|
|
|
private $parentLevel = 1; |
24
|
|
|
/** @var ListItem|null */ |
25
|
|
|
private $lastListItem; |
26
|
|
|
|
27
|
3 |
|
public function __construct(TableOfContents $toc) |
28
|
|
|
{ |
29
|
3 |
|
$this->parentListBlock = $toc; |
30
|
3 |
|
} |
31
|
|
|
|
32
|
3 |
|
public function addItem(int $level, ListItem $listItemToAdd): void |
33
|
|
|
{ |
34
|
3 |
|
while ($level > $this->parentLevel) { |
35
|
|
|
// Descend downwards, creating new ListBlocks if needed, until we reach the correct depth |
36
|
3 |
|
if ($this->lastListItem === null) { |
37
|
3 |
|
$this->lastListItem = new ListItem($this->parentListBlock->getListData()); |
38
|
3 |
|
$this->parentListBlock->appendChild($this->lastListItem); |
39
|
|
|
} |
40
|
|
|
|
41
|
3 |
|
$newListBlock = new ListBlock($this->parentListBlock->getListData()); |
42
|
3 |
|
$this->lastListItem->appendChild($newListBlock); |
43
|
3 |
|
$this->parentListBlock = $newListBlock; |
44
|
3 |
|
$this->lastListItem = null; |
45
|
|
|
|
46
|
3 |
|
$this->parentLevel++; |
47
|
|
|
} |
48
|
|
|
|
49
|
3 |
|
while ($level < $this->parentLevel) { |
50
|
|
|
// Search upwards for the previous parent list block |
51
|
3 |
|
while (true) { |
52
|
3 |
|
$this->parentListBlock = $this->parentListBlock->parent(); |
53
|
3 |
|
if ($this->parentListBlock instanceof ListBlock) { |
54
|
3 |
|
break; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
3 |
|
$this->parentLevel--; |
59
|
|
|
} |
60
|
|
|
|
61
|
3 |
|
$this->parentListBlock->appendChild($listItemToAdd); |
62
|
|
|
|
63
|
3 |
|
$this->lastListItem = $listItemToAdd; |
64
|
3 |
|
} |
65
|
|
|
} |
66
|
|
|
|