1<?php
2
3/*
4 * This file is part of the league/commonmark package.
5 *
6 * (c) Colin O'Dell <colinodell@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace League\CommonMark\Extension\TableOfContents\Normalizer;
13
14use League\CommonMark\Block\Element\ListBlock;
15use League\CommonMark\Block\Element\ListItem;
16use League\CommonMark\Extension\TableOfContents\Node\TableOfContents;
17
18final 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    public function __construct(TableOfContents $toc)
28    {
29        $this->parentListBlock = $toc;
30    }
31
32    public function addItem(int $level, ListItem $listItemToAdd): void
33    {
34        while ($level > $this->parentLevel) {
35            // Descend downwards, creating new ListBlocks if needed, until we reach the correct depth
36            if ($this->lastListItem === null) {
37                $this->lastListItem = new ListItem($this->parentListBlock->getListData());
38                $this->parentListBlock->appendChild($this->lastListItem);
39            }
40
41            $newListBlock = new ListBlock($this->parentListBlock->getListData());
42            $newListBlock->setStartLine($listItemToAdd->getStartLine());
43            $newListBlock->setEndLine($listItemToAdd->getEndLine());
44            $this->lastListItem->appendChild($newListBlock);
45            $this->parentListBlock = $newListBlock;
46            $this->lastListItem = null;
47
48            $this->parentLevel++;
49        }
50
51        while ($level < $this->parentLevel) {
52            // Search upwards for the previous parent list block
53            while (true) {
54                $this->parentListBlock = $this->parentListBlock->parent();
55                if ($this->parentListBlock instanceof ListBlock) {
56                    break;
57                }
58            }
59
60            $this->parentLevel--;
61        }
62
63        $this->parentListBlock->appendChild($listItemToAdd);
64
65        $this->lastListItem = $listItemToAdd;
66    }
67}
68
69// Trigger autoload without causing a deprecated error
70\class_exists(TableOfContents::class);
71