2023-11-23 22:29:07 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace BookStack\Entities\Tools;
|
|
|
|
|
|
|
|
use BookStack\Util\HtmlDocument;
|
|
|
|
use DOMNode;
|
|
|
|
|
|
|
|
class PageIncludeContent
|
|
|
|
{
|
|
|
|
protected static array $topLevelTags = ['table', 'ul', 'ol', 'pre'];
|
|
|
|
|
|
|
|
/**
|
2023-11-28 05:38:43 +08:00
|
|
|
* @param DOMNode[] $contents
|
|
|
|
* @param bool $isInline
|
2023-11-23 22:29:07 +08:00
|
|
|
*/
|
|
|
|
public function __construct(
|
2023-11-28 05:38:43 +08:00
|
|
|
protected array $contents,
|
|
|
|
protected bool $isInline,
|
2023-11-23 22:29:07 +08:00
|
|
|
) {
|
|
|
|
}
|
|
|
|
|
2023-11-28 05:38:43 +08:00
|
|
|
public static function fromHtmlAndTag(string $html, PageIncludeTag $tag): self
|
2023-11-23 22:29:07 +08:00
|
|
|
{
|
|
|
|
if (empty($html)) {
|
2023-11-28 05:38:43 +08:00
|
|
|
return new self([], true);
|
2023-11-23 22:29:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
$doc = new HtmlDocument($html);
|
|
|
|
|
|
|
|
$sectionId = $tag->getSectionId();
|
|
|
|
if (!$sectionId) {
|
2023-11-28 05:38:43 +08:00
|
|
|
$contents = [...$doc->getBodyChildren()];
|
|
|
|
return new self($contents, false);
|
2023-11-23 22:29:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
$section = $doc->getElementById($sectionId);
|
|
|
|
if (!$section) {
|
2023-11-28 05:38:43 +08:00
|
|
|
return new self([], true);
|
2023-11-23 22:29:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
$isTopLevel = in_array(strtolower($section->nodeName), static::$topLevelTags);
|
2023-11-28 05:38:43 +08:00
|
|
|
$contents = $isTopLevel ? [$section] : [...$section->childNodes];
|
|
|
|
return new self($contents, !$isTopLevel);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function fromInlineHtml(string $html): self
|
|
|
|
{
|
|
|
|
if (empty($html)) {
|
|
|
|
return new self([], true);
|
|
|
|
}
|
|
|
|
|
|
|
|
$doc = new HtmlDocument($html);
|
|
|
|
|
|
|
|
return new self([...$doc->getBodyChildren()], true);
|
2023-11-23 22:29:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
public function isInline(): bool
|
|
|
|
{
|
2023-11-28 05:38:43 +08:00
|
|
|
return $this->isInline;
|
2023-11-23 22:29:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
public function isEmpty(): bool
|
|
|
|
{
|
|
|
|
return empty($this->contents);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return DOMNode[]
|
|
|
|
*/
|
|
|
|
public function toDomNodes(): array
|
|
|
|
{
|
|
|
|
return $this->contents;
|
|
|
|
}
|
2023-11-28 05:38:43 +08:00
|
|
|
|
|
|
|
public function toHtml(): string
|
|
|
|
{
|
|
|
|
$html = '';
|
|
|
|
|
|
|
|
foreach ($this->contents as $content) {
|
|
|
|
$html .= $content->ownerDocument->saveHTML($content);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $html;
|
|
|
|
}
|
2023-11-23 22:29:07 +08:00
|
|
|
}
|