-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHtmlFragment.php
More file actions
222 lines (177 loc) · 6.6 KB
/
Copy pathHtmlFragment.php
File metadata and controls
222 lines (177 loc) · 6.6 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<?php
namespace TestMonitor\Revisable\Renderers\Support;
use DOMDocument;
use DOMElement;
use DOMNode;
use DOMText;
use DOMXPath;
/**
* A small, fluent wrapper around DOMDocument for editing an HTML snippet in place.
*
* Parses the snippet once, exposes a handful of purpose-built mutations, and
* serializes it back out — keeping DOM/libxml mechanics out of the caller.
*/
class HtmlFragment
{
protected DOMDocument $dom;
protected DOMElement $root;
protected DOMXPath $xpath;
public function __construct(string $html)
{
$this->dom = new DOMDocument;
$previousSetting = libxml_use_internal_errors(true);
$this->dom->loadHTML(
'<?xml encoding="utf-8"?><div id="__root__">' . $html . '</div>',
LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
);
libxml_use_internal_errors($previousSetting);
$this->xpath = new DOMXPath($this->dom);
$this->root = $this->xpath->query('//*[@id="__root__"]')->item(0);
}
/**
* Rename every element matched by $query to $tagName, preserving its attributes and children.
*/
public function renameElements(string $query, string $tagName): static
{
foreach (iterator_to_array($this->xpath->query($query)) as $element) {
$replacement = $this->dom->createElement($tagName);
foreach (iterator_to_array($element->attributes) as $attribute) {
$replacement->setAttribute($attribute->name, $attribute->value);
}
while ($element->firstChild) {
$replacement->appendChild($element->firstChild);
}
$element->parentNode->replaceChild($replacement, $element);
}
return $this;
}
/**
* Remove every element matched by $query, along with its content.
*/
public function removeElements(string $query): static
{
foreach (iterator_to_array($this->xpath->query($query)) as $element) {
$element->parentNode->removeChild($element);
}
return $this;
}
/**
* Drop an attribute from every element matched by $query.
*/
public function removeAttribute(string $query, string $attribute): static
{
foreach ($this->xpath->query($query) as $element) {
$element->removeAttribute($attribute);
}
return $this;
}
/**
* Repeatedly remove elements matched by $selector once they're left with no visible
* content — e.g. a <ul> whose items were all removed. Repeats since emptying one
* element can in turn leave its own parent empty too.
*/
public function removeEmptyElements(string $selector): static
{
do {
$removed = 0;
foreach (iterator_to_array($this->xpath->query($selector)) as $element) {
if (! $this->isBlank($element)) {
continue;
}
$element->parentNode->removeChild($element);
$removed++;
}
} while ($removed > 0);
return $this;
}
/**
* Remove elements matched by $selector that are left with no visible content once their
* $descendantTag descendants are disregarded — regardless of how deeply nested they are.
* Elements that already had no visible content before this call are left untouched.
*/
public function removeElementsEmptiedBy(string $selector, string $descendantTag): static
{
$candidates = iterator_to_array($this->xpath->query($selector));
$preexistingEmpty = [];
foreach ($candidates as $element) {
if ($this->isBlank($element)) {
$preexistingEmpty[spl_object_id($element)] = true;
}
}
// Deepest elements first, so clearing an inner element can empty out its ancestor too.
foreach (array_reverse($candidates) as $element) {
if (isset($preexistingEmpty[spl_object_id($element)])) {
continue;
}
// A nested candidate that held all of this element's content was just removed.
if ($this->isBlank($element)) {
$element->parentNode->removeChild($element);
continue;
}
if ($this->xpath->query(".//{$descendantTag}", $element)->length === 0) {
continue;
}
if (trim($this->textOutside($element, $descendantTag)) === '') {
$element->parentNode->removeChild($element);
}
}
return $this;
}
/**
* Serialize the fragment back into an HTML string.
*/
public function toHtml(): string
{
// Childless elements would otherwise have their closing tag silently dropped by
// libxml's HTML serializer (e.g. <li></li> would come back out as just <li>); a
// placeholder text node forces it to always emit both tags.
foreach (iterator_to_array($this->xpath->query('.//*[not(node())]', $this->root)) as $element) {
$element->appendChild($this->dom->createTextNode(''));
}
$html = '';
foreach ($this->root->childNodes as $child) {
$html .= $this->dom->saveHTML($child);
}
return $html;
}
/**
* Concatenate the visible text directly inside $element, excluding any text nested
* inside a descendant $tagName element (e.g. the <ins>/<del> being disregarded).
*/
protected function textOutside(DOMNode $element, string $tagName): string
{
$text = '';
foreach ($this->xpath->query('.//text()', $element) as $textNode) {
if (! $this->hasAncestorNamed($textNode, $tagName, $element)) {
$text .= $textNode->textContent;
}
}
return $text;
}
/**
* Determine whether $node has an ancestor named $tagName before reaching $boundary.
*/
protected function hasAncestorNamed(DOMNode $node, string $tagName, DOMNode $boundary): bool
{
$ancestor = $node->parentNode;
while ($ancestor !== null && $ancestor !== $boundary) {
if ($ancestor->nodeName === $tagName) {
return true;
}
$ancestor = $ancestor->parentNode;
}
return false;
}
/**
* Determine whether $element has no content beyond whitespace-only text.
*/
protected function isBlank(DOMNode $element): bool
{
foreach ($element->childNodes as $child) {
if (! ($child instanceof DOMText) || trim($child->wholeText) !== '') {
return false;
}
}
return true;
}
}