]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PageIncludeContent.php
Opensearch: Fixed XML declaration when php short tags enabled
[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      * @param DOMNode[] $contents
14      * @param bool $isInline
15      */
16     public function __construct(
17         protected array $contents,
18         protected bool $isInline,
19     ) {
20     }
21
22     public static function fromHtmlAndTag(string $html, PageIncludeTag $tag): self
23     {
24         if (empty($html)) {
25             return new self([], true);
26         }
27
28         $doc = new HtmlDocument($html);
29
30         $sectionId = $tag->getSectionId();
31         if (!$sectionId) {
32             $contents = [...$doc->getBodyChildren()];
33             return new self($contents, false);
34         }
35
36         $section = $doc->getElementById($sectionId);
37         if (!$section) {
38             return new self([], true);
39         }
40
41         $isTopLevel = in_array(strtolower($section->nodeName), static::$topLevelTags);
42         $contents = $isTopLevel ? [$section] : [...$section->childNodes];
43         return new self($contents, !$isTopLevel);
44     }
45
46     public static function fromInlineHtml(string $html): self
47     {
48         if (empty($html)) {
49             return new self([], true);
50         }
51
52         $doc = new HtmlDocument($html);
53
54         return new self([...$doc->getBodyChildren()], true);
55     }
56
57     public function isInline(): bool
58     {
59         return $this->isInline;
60     }
61
62     public function isEmpty(): bool
63     {
64         return empty($this->contents);
65     }
66
67     /**
68      * @return DOMNode[]
69      */
70     public function toDomNodes(): array
71     {
72         return $this->contents;
73     }
74
75     public function toHtml(): string
76     {
77         $html = '';
78
79         foreach ($this->contents as $content) {
80             $html .= $content->ownerDocument->saveHTML($content);
81         }
82
83         return $html;
84     }
85 }