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