]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PageIncludeContent.php
Includes: Switched page to new system
[bookstack] / app / Entities / Tools / PageIncludeContent.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\Util\HtmlDocument;
6 use DOMNode;
7
8 class PageIncludeContent
9 {
10     protected static array $topLevelTags = ['table', 'ul', 'ol', 'pre'];
11
12     /**
13      * @var DOMNode[]
14      */
15     protected array $contents = [];
16
17     protected bool $isTopLevel = false;
18
19     public function __construct(
20         string $html,
21         PageIncludeTag $tag,
22     ) {
23         $this->parseHtml($html, $tag);
24     }
25
26     protected function parseHtml(string $html, PageIncludeTag $tag): void
27     {
28         if (empty($html)) {
29             return;
30         }
31
32         $doc = new HtmlDocument($html);
33
34         $sectionId = $tag->getSectionId();
35         if (!$sectionId) {
36             $this->contents = [...$doc->getBodyChildren()];
37             $this->isTopLevel = true;
38             return;
39         }
40
41         $section = $doc->getElementById($sectionId);
42         if (!$section) {
43             return;
44         }
45
46         $isTopLevel = in_array(strtolower($section->nodeName), static::$topLevelTags);
47         $this->isTopLevel = $isTopLevel;
48         $this->contents = $isTopLevel ? [$section] : [...$section->childNodes];
49     }
50
51     public function isInline(): bool
52     {
53         return !$this->isTopLevel;
54     }
55
56     public function isEmpty(): bool
57     {
58         return empty($this->contents);
59     }
60
61     /**
62      * @return DOMNode[]
63      */
64     public function toDomNodes(): array
65     {
66         return $this->contents;
67     }
68 }