generated from spatie/package-skeleton-laravel
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathHtmlConversion.php
62 lines (47 loc) · 1.78 KB
/
HtmlConversion.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
namespace Tonysm\RichTextLaravel;
use DOMDocument;
use DOMElement;
class HtmlConversion
{
public static function nodeElementToHtml(DOMElement $node): string
{
return $node->ownerDocument->saveHTML($node);
}
public static function nodeToHtml(DOMDocument $node): string
{
return preg_replace("#</?rich-text-root>\n*#", '', $node->saveHTML($node->documentElement));
}
public static function fragmentForHtml(?string $html = null): Fragment
{
$document = static::document($html);
return new Fragment($document);
}
public static function createElement($tagName, array $attributes = []): DOMElement
{
$element = static::document()->createElement($tagName);
foreach ($attributes as $attr => $value) {
$element->setAttribute($attr, $value);
}
return $element;
}
public static function document(?string $html = null): DOMDocument
{
libxml_use_internal_errors(true);
$document = new DOMDocument('1.0', 'UTF-8');
if ($html) {
// We're using a hack here to force the document encoding properly.
// Then, we're going to remove the encoding tag from the document
// right before returning it so we can have a clean document.
// @see http://php.net/manual/en/domdocument.loadhtml.php#95251
$document->loadHTML("<?xml encoding=\"UTF-8\"><rich-text-root>{$html}</rich-text-root>", LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
foreach ($document->childNodes as $item) {
if ($item->nodeType == XML_PI_NODE) {
$document->removeChild($item);
}
}
$document->encoding = 'UTF-8';
}
return $document;
}
}