Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 126
0.00% covered (danger)
0.00%
0 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Serializer
0.00% covered (danger)
0.00%
0 / 126
0.00% covered (danger)
0.00%
0 / 19
2550
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getResult
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getRootNode
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getParentNode
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getLastChild
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 startDocument
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 endDocument
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 interpretPlacement
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 characters
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
 insertElement
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
30
 endTag
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
 serializeNode
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 doctype
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 comment
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 error
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 mergeAttributes
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 removeNode
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 reparentChildren
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 dump
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\RemexHtml\Serializer;
5
6use Wikimedia\RemexHtml\PropGuard;
7use Wikimedia\RemexHtml\Tokenizer\Attributes;
8use Wikimedia\RemexHtml\Tokenizer\PlainAttributes;
9use Wikimedia\RemexHtml\TreeBuilder\Element;
10use Wikimedia\RemexHtml\TreeBuilder\TreeBuilder;
11
12/**
13 * A TreeHandler which builds a serialized representation of a document, by
14 * encoding elements when the end tags are seen. This is faster than building
15 * a DOM and then serializing it, even if you use DOMDocument::saveHTML().
16 */
17class Serializer implements AbstractSerializer {
18    use PropGuard;
19
20    /**
21     * A node corresponding to the Document
22     * @var SerializerNode
23     */
24    private $root;
25
26    /**
27     * The error callback
28     *
29     * @var callable|null
30     */
31    private $errorCallback;
32
33    /**
34     * The Formatter implementation
35     */
36    private Formatter $formatter;
37
38    /**
39     * All active SerializerNode objects in an array, so that they can be
40     * referred to by integer indexes. This is a way to emulate weak references,
41     * to avoid circular references, allowing nodes to be freed.
42     *
43     * @var SerializerNode[]
44     * @internal
45     */
46    protected $nodes = [];
47
48    /**
49     * True if we are parsing a fragment. The children of the <html> element
50     * will be serialized, instead of the whole document.
51     *
52     * @var bool
53     */
54    private $isFragment;
55
56    /**
57     * The result string
58     *
59     * @var string
60     */
61    private $result = '';
62
63    /**
64     * Constructor
65     *
66     * @param Formatter $formatter
67     * @param callable|null $errorCallback A function which is called with the
68     *   details of each parse error
69     */
70    public function __construct( Formatter $formatter, $errorCallback = null ) {
71        $this->formatter = $formatter;
72        $this->errorCallback = $errorCallback;
73    }
74
75    /**
76     * Get the final string. This can only be called after endDocument() is received.
77     * @return string
78     */
79    public function getResult() {
80        return $this->result;
81    }
82
83    /**
84     * Get the root SerializerNode.
85     *
86     * @return SerializerNode
87     */
88    public function getRootNode() {
89        return $this->root;
90    }
91
92    /**
93     * Get the parent SerializerNode of a given SerializerNode
94     *
95     * @param SerializerNode $node
96     * @return SerializerNode
97     */
98    public function getParentNode( SerializerNode $node ) {
99        return $this->nodes[$node->parentId];
100    }
101
102    /**
103     * Get the last child of a given SerializerNode
104     *
105     * @param SerializerNode $node
106     * @return SerializerNode|string|null
107     */
108    public function getLastChild( SerializerNode $node ) {
109        return array_last( $node->children );
110    }
111
112    /** @inheritDoc */
113    public function startDocument( $fragmentNamespace, $fragmentName ) {
114        $this->root = new SerializerNode( 0, 0, '', '', new PlainAttributes, false );
115        $this->nodes = [ $this->root ];
116        $this->isFragment = $fragmentNamespace !== null;
117        $this->result = $this->formatter->startDocument( $fragmentNamespace, $fragmentName );
118    }
119
120    /** @inheritDoc */
121    public function endDocument( $pos ) {
122        if ( $this->isFragment ) {
123            $root = $this->root->children[0];
124        } else {
125            $root = $this->root;
126        }
127        foreach ( $root->children as $childIndex => $child ) {
128            if ( is_string( $child ) ) {
129                $this->result .= $child;
130            } else {
131                $this->result .= $this->serializeNode( $root, $child, false );
132            }
133        }
134        // @phan-suppress-next-line PhanTypeMismatchPropertyProbablyReal
135        $this->root = null;
136        $this->nodes = [];
137    }
138
139    /**
140     * @param int $preposition
141     * @param Element $refElement
142     * @return array
143     */
144    protected function interpretPlacement( $preposition, $refElement ) {
145        if ( $preposition === TreeBuilder::ROOT ) {
146            return [ $this->root, null ];
147        }
148        if ( $refElement instanceof Element ) {
149            $refNode = $refElement->userData;
150        } elseif ( $refElement instanceof SerializerNode ) {
151            $refNode = $refElement;
152        } else {
153            throw new SerializerError( "Invalid type of ref element" );
154        }
155        if ( $preposition === TreeBuilder::BEFORE ) {
156            return [ $this->nodes[$refNode->parentId], $refNode ];
157        } else {
158            return [ $refNode, $refNode ];
159        }
160    }
161
162    /** @inheritDoc */
163    public function characters( $preposition, $refElement, $text, $start, $length,
164        $sourceStart, $sourceLength
165    ) {
166        [ $parent, $refNode ] = $this->interpretPlacement( $preposition, $refElement );
167        $encoded = (string)$this->formatter->characters( $parent, $text, $start, $length );
168
169        $children =& $parent->children;
170        // @phan-suppress-next-line PhanCoalescingNeverNull
171        $lastChildIndex = array_key_last( $children ) ?? -1;
172        $lastChild = array_last( $children );
173
174        if ( $preposition === TreeBuilder::BEFORE ) {
175            // Insert before element
176            if ( $lastChild !== $refNode ) {
177                $refIndex = array_search( $refNode, $children, true );
178                throw new SerializerError( "invalid insert position $refIndex/$lastChildIndex" );
179            }
180            $children[$lastChildIndex] = $encoded;
181            $children[] = $refNode;
182        } else {
183            // Append to the list of children
184            if ( is_string( $lastChild ) ) {
185                $children[$lastChildIndex] .= $encoded;
186            } else {
187                $children[] = $encoded;
188            }
189        }
190    }
191
192    /**
193     * Insert an element
194     *
195     * @param int $preposition
196     * @param Element|SerializerNode|null $refElement
197     * @param Element $element
198     * @param bool $void
199     * @param int $sourceStart
200     * @param int $sourceLength
201     */
202    public function insertElement( $preposition, $refElement, Element $element, $void,
203        $sourceStart, $sourceLength
204    ) {
205        [ $parent, $refNode ] = $this->interpretPlacement( $preposition, $refElement );
206        $children =& $parent->children;
207        // @phan-suppress-next-line PhanCoalescingNeverNull
208        $lastChildIndex = array_key_last( $children ) ?? -1;
209        $lastChild = array_last( $children );
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[] = $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        // @phan-suppress-next-line PhanCoalescingNeverNull
303        $lastChildIndex = array_key_last( $children ) ?? -1;
304        $lastChild = array_last( $children );
305
306        if ( $preposition === TreeBuilder::BEFORE ) {
307            // Insert before element
308            if ( $lastChild !== $refNode ) {
309                throw new SerializerError( "invalid insert position" );
310            }
311            $children[$lastChildIndex] = $encoded;
312            $children[] = $refNode;
313        } else {
314            // Append to the list of children
315            if ( is_string( $lastChild ) ) {
316                $children[$lastChildIndex] .= $encoded;
317            } else {
318                $children[] = $encoded;
319            }
320        }
321    }
322
323    /** @inheritDoc */
324    public function error( $text, $pos ) {
325        if ( $this->errorCallback ) {
326            ( $this->errorCallback )( $text, $pos );
327        }
328    }
329
330    /** @inheritDoc */
331    public function mergeAttributes( Element $element, Attributes $attrs, $sourceStart ) {
332        $element->attrs->merge( $attrs );
333        if ( $element->userData instanceof SerializerNode ) {
334            $element->userData->attrs = $element->attrs;
335        }
336    }
337
338    /** @inheritDoc */
339    public function removeNode( Element $element, $sourceStart ) {
340        $self = $element->userData;
341        $parent = $this->nodes[$self->parentId];
342        $children =& $parent->children;
343        for ( $index = count( $children ) - 1; $index >= 0; $index-- ) {
344            if ( $children[$index] === $self ) {
345                $children[$index] = '';
346                return;
347            }
348        }
349        throw new SerializerError( "cannot find element to remove" );
350    }
351
352    /** @inheritDoc */
353    public function reparentChildren( Element $element, Element $newParent, $sourceStart ) {
354        $self = $element->userData;
355        '@phan-var SerializerNode $self';
356        $children = $self->children;
357        $self->children = [];
358        $this->insertElement( TreeBuilder::UNDER, $element, $newParent, false, $sourceStart, 0 );
359        $newParentNode = $newParent->userData;
360        '@phan-var SerializerNode $newParentNode';
361        $newParentId = $newParentNode->id;
362        foreach ( $children as $child ) {
363            if ( $child instanceof SerializerNode ) {
364                $child->parentId = $newParentId;
365            }
366        }
367        $newParentNode->children = $children;
368    }
369
370    /**
371     * Get a text representation of the current state of the serializer, for
372     * debugging.
373     *
374     * @return string
375     */
376    public function dump() {
377        $s = $this->serializeNode( $this->root, $this->root, false );
378        return substr( $s, 2, -3 ) . "\n";
379    }
380}