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