Debian Codegraph @

vendor/wikimedia/remex-html/src/Serializer/Serializer.php

raw
1 <?php
2
3 namespace Wikimedia\RemexHtml\Serializer;
4
5 use Wikimedia\RemexHtml\PropGuard;
6 use Wikimedia\RemexHtml\Tokenizer\Attributes;
7 use Wikimedia\RemexHtml\Tokenizer\PlainAttributes;
8 use Wikimedia\RemexHtml\TreeBuilder\Element;
9 use Wikimedia\RemexHtml\TreeBuilder\TreeBuilder;
10
11 /**
12 * A TreeHandler which builds a serialized representation of a document, by
13 * encoding elements when the end tags are seen. This is faster than building
14 * a DOM and then serializing it, even if you use DOMDocument::saveHTML().
15 */
16 class Serializer implements AbstractSerializer {
17 use PropGuard;
18
19 /**
20 * A node corresponding to the Document
21 * @var SerializerNode
22 */
23 private $root;
24
25 /**
26 * The error callback
27 *
28 * @var callable|null
29 */
30 private $errorCallback;
31
32 /**
33 * The Formatter implementation
34 */
35 private Formatter $formatter;
36
37 /**
38 * All active SerializerNode objects in an array, so that they can be
39 * referred to by integer indexes. This is a way to emulate weak references,
40 * to avoid circular references, allowing nodes to be freed.
41 *
42 * @var SerializerNode[]
43 * @internal
44 */
45 protected $nodes = [];
46
47 /**
48 * True if we are parsing a fragment. The children of the <html> element
49 * will be serialized, instead of the whole document.
50 *
51 * @var bool
52 */
53 private $isFragment;
54
55 /**
56 * The result string
57 *
58 * @var string
59 */
60 private $result = '';
61
62 /**
63 * Constructor
64 *
65 * @param Formatter $formatter
66 * @param callable|null $errorCallback A function which is called with the
67 * details of each parse error
68 */
69 public function __construct( Formatter $formatter, $errorCallback = null ) {
70 $this->formatter = $formatter;
71 $this->errorCallback = $errorCallback;
72 }
73
74 /**
75 * Get the final string. This can only be called after endDocument() is received.
76 * @return string
77 */
78 public function getResult() {
79 return $this->result;
80 }
81
82 /**
83 * Get the root SerializerNode.
84 *
85 * @return SerializerNode
86 */
87 public function getRootNode() {
88 return $this->root;
89 }
90
91 /**
92 * Get the parent SerializerNode of a given SerializerNode
93 *
94 * @param SerializerNode $node
95 * @return SerializerNode
96 */
97 public function getParentNode( SerializerNode $node ) {
98 return $this->nodes[$node->parentId];
99 }
100
101 /**
102 * Get the last child of a given SerializerNode
103 *
104 * @param SerializerNode $node
105 * @return SerializerNode|string|null
106 */
107 public function getLastChild( SerializerNode $node ) {
108 $children = $node->children;
109 $lastChildIndex = count( $children ) - 1;
110 $lastChild = $lastChildIndex >= 0 ? $children[$lastChildIndex] : null;
111 return $lastChild;
112 }
113
114 /** @inheritDoc */
115 public function startDocument( $fragmentNamespace, $fragmentName ) {
116 $this->root = new SerializerNode( 0, 0, '', '', new PlainAttributes, false );
117 $this->nodes = [ $this->root ];
118 $this->isFragment = $fragmentNamespace !== null;
119 $this->result = $this->formatter->startDocument( $fragmentNamespace, $fragmentName );
120 }
121
122 /** @inheritDoc */
123 public function endDocument( $pos ) {
124 if ( $this->isFragment ) {
125 $root = $this->root->children[0];
126 } else {
127 $root = $this->root;
128 }
129 foreach ( $root->children as $childIndex => $child ) {
130 if ( is_string( $child ) ) {
131 $this->result .= $child;
132 } else {
133 $this->result .= $this->serializeNode( $root, $child, false );
134 }
135 }
136 // @phan-suppress-next-line PhanTypeMismatchPropertyProbablyReal
137 $this->root = null;
138 $this->nodes = [];
139 }
140
141 /**
142 * @param int $preposition
143 * @param Element $refElement
144 * @return array
145 */
146 protected function interpretPlacement( $preposition, $refElement ) {
147 if ( $preposition === TreeBuilder::ROOT ) {
148 return [ $this->root, null ];
149 }
150 if ( $refElement instanceof Element ) {
151 $refNode = $refElement->userData;
152 } elseif ( $refElement instanceof SerializerNode ) {
153 $refNode = $refElement;
154 } else {
155 throw new SerializerError( "Invalid type of ref element" );
156 }
157 if ( $preposition === TreeBuilder::BEFORE ) {
158 return [ $this->nodes[$refNode->parentId], $refNode ];
159 } else {
160 return [ $refNode, $refNode ];
161 }
162 }
163
164 /** @inheritDoc */
165 public function characters( $preposition, $refElement, $text, $start, $length,
166 $sourceStart, $sourceLength
167 ) {
168 [ $parent, $refNode ] = $this->interpretPlacement( $preposition, $refElement );
169 $encoded = (string)$this->formatter->characters( $parent, $text, $start, $length );
170
171 $children =& $parent->children;
172 $lastChildIndex = count( $children ) - 1;
173 $lastChild = $lastChildIndex >= 0 ? $children[$lastChildIndex] : null;
174
175 if ( $preposition === TreeBuilder::BEFORE ) {
176 // Insert before element
177 if ( $lastChild !== $refNode ) {
178 $refIndex = array_search( $refNode, $children, true );
179 throw new SerializerError( "invalid insert position $refIndex/$lastChildIndex" );
180 }
181 $children[$lastChildIndex] = $encoded;
182 $children[$lastChildIndex + 1] = $refNode;
183 } else {
184 // Append to the list of children
185 if ( is_string( $lastChild ) ) {
186 $children[$lastChildIndex] .= $encoded;
187 } else {
188 $children[] = $encoded;
189 }
190 }
191 }
192
193 /**
194 * Insert an element
195 *
196 * @param int $preposition
197 * @param Element|SerializerNode|null $refElement
198 * @param Element $element
199 * @param bool $void
200 * @param int $sourceStart
201 * @param int $sourceLength
202 */
203 public function insertElement( $preposition, $refElement, Element $element, $void,
204 $sourceStart, $sourceLength
205 ) {
206 [ $parent, $refNode ] = $this->interpretPlacement( $preposition, $refElement );
207 $children =& $parent->children;
208 $lastChildIndex = count( $children ) - 1;
209 $lastChild = $lastChildIndex >= 0 ? $children[$lastChildIndex] : null;
210
211 if ( $element->userData ) {
212 // This element has already been inserted, this is a reparenting operation
213 $self = $element->userData;
214 '@phan-var SerializerNode $self'; /** @var SerializerNode $self */
215 $oldParent = $this->nodes[$self->parentId];
216 $oldChildren =& $oldParent->children;
217 $oldChildIndex = array_search( $self, $oldChildren, true );
218 if ( $oldChildIndex === false ) {
219 throw new SerializerError( "cannot find node to reparent: " .
220 $element->getDebugTag() );
221 }
222 // Remove from the old parent, update parent pointer
223 $oldChildren[$oldChildIndex] = '';
224 $self->parentId = $parent->id;
225 } else {
226 // Inserting an element which has not been seen before
227 $id = $element->uid;
228 $self = new SerializerNode( $id, $parent->id, $element->namespace,
229 $element->name, $element->attrs, $void );
230 $this->nodes[$id] = $element->userData = $self;
231 }
232
233 if ( $preposition === TreeBuilder::BEFORE ) {
234 // Insert before element
235 if ( $lastChild !== $refNode ) {
236 $refIndex = array_search( $refNode, $children, true );
237 throw new SerializerError( "invalid insert position $refIndex/$lastChildIndex" );
238 }
239 $children[$lastChildIndex] = $self;
240 $children[$lastChildIndex + 1] = $refNode;
241 } else {
242 // Append to the list of children
243 $children[] = $self;
244 }
245 }
246
247 /** @inheritDoc */
248 public function endTag( Element $element, $sourceStart, $sourceLength ) {
249 if ( $element->htmlName === 'head' || $element->isVirtual ) {
250 // <head> elements are immortal
251 return;
252 }
253 $self = $element->userData;
254 $parent = $this->nodes[$self->parentId];
255 $children =& $parent->children;
256 for ( $index = count( $children ) - 1; $index >= 0; $index-- ) {
257 if ( $children[$index] === $self ) {
258 $children[$index] = $this->serializeNode( $parent, $self, true );
259 return;
260 }
261 }
262 // Ignore requests to end non-existent elements (this happens sometimes)
263 }
264
265 /**
266 * Serialize a specific node
267 *
268 * @param SerializerNode $parent The parent of $node
269 * @param SerializerNode $node The node to serialize
270 * @param bool $destroy If true, the node and its descendants will be removed from $this->nodes
271 * @return string
272 */
273 private function serializeNode( SerializerNode $parent, SerializerNode $node, $destroy ) {
274 if ( $node->void ) {
275 $contents = null;
276 } else {
277 $contents = '';
278 foreach ( $node->children as $childIndex => $child ) {
279 if ( is_string( $child ) ) {
280 $contents .= $child;
281 } else {
282 $contents .= $this->serializeNode( $node, $child, $destroy );
283 }
284 }
285 }
286 if ( $destroy ) {
287 unset( $this->nodes[$node->id] );
288 }
289 return $this->formatter->element( $parent, $node, $contents );
290 }
291
292 /** @inheritDoc */
293 public function doctype( $name, $public, $system, $quirks, $sourceStart, $sourceLength ) {
294 $this->result .= $this->formatter->doctype( $name, $public, $system );
295 }
296
297 /** @inheritDoc */
298 public function comment( $preposition, $refElement, $text, $sourceStart, $sourceLength ) {
299 [ $parent, $refNode ] = $this->interpretPlacement( $preposition, $refElement );
300 $encoded = $this->formatter->comment( $parent, $text );
301 $children =& $parent->children;
302 $lastChildIndex = count( $children ) - 1;
303 $lastChild = $lastChildIndex >= 0 ? $children[$lastChildIndex] : null;
304
305 if ( $preposition === TreeBuilder::BEFORE ) {
306 // Insert before element
307 if ( $lastChild !== $refNode ) {
308 throw new SerializerError( "invalid insert position" );
309 }
310 $children[$lastChildIndex] = $encoded;
311 $children[$lastChildIndex + 1] = $refNode;
312 } else {
313 // Append to the list of children
314 if ( is_string( $lastChild ) ) {
315 $children[$lastChildIndex] .= $encoded;
316 } else {
317 $children[] = $encoded;
318 }
319 }
320 }
321
322 /** @inheritDoc */
323 public function error( $text, $pos ) {
324 if ( $this->errorCallback ) {
325 ( $this->errorCallback )( $text, $pos );
326 }
327 }
328
329 /** @inheritDoc */
330 public function mergeAttributes( Element $element, Attributes $attrs, $sourceStart ) {
331 $element->attrs->merge( $attrs );
332 if ( $element->userData instanceof SerializerNode ) {
333 $element->userData->attrs = $element->attrs;
334 }
335 }
336
337 /** @inheritDoc */
338 public function removeNode( Element $element, $sourceStart ) {
339 $self = $element->userData;
340 $parent = $this->nodes[$self->parentId];
341 $children =& $parent->children;
342 for ( $index = count( $children ) - 1; $index >= 0; $index-- ) {
343 if ( $children[$index] === $self ) {
344 $children[$index] = '';
345 return;
346 }
347 }
348 throw new SerializerError( "cannot find element to remove" );
349 }
350
351 /** @inheritDoc */
352 public function reparentChildren( Element $element, Element $newParent, $sourceStart ) {
353 $self = $element->userData;
354 '@phan-var SerializerNode $self';
355 $children = $self->children;
356 $self->children = [];
357 $this->insertElement( TreeBuilder::UNDER, $element, $newParent, false, $sourceStart, 0 );
358 $newParentNode = $newParent->userData;
359 '@phan-var SerializerNode $newParentNode';
360 $newParentId = $newParentNode->id;
361 foreach ( $children as $child ) {
362 if ( $child instanceof SerializerNode ) {
363 $child->parentId = $newParentId;
364 }
365 }
366 $newParentNode->children = $children;
367 }
368
369 /**
370 * Get a text representation of the current state of the serializer, for
371 * debugging.
372 *
373 * @return string
374 */
375 public function dump() {
376 $s = $this->serializeNode( $this->root, $this->root, false );
377 return substr( $s, 2, -3 ) . "\n";
378 }
379 }