Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 141
0.00% covered (danger)
0.00%
0 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
CachingStack
0.00% covered (danger)
0.00%
0 / 141
0.00% covered (danger)
0.00%
0 / 17
5256
0.00% covered (danger)
0.00%
0 / 1
 getScopeTypesToStack
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
462
 push
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
42
 pop
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
 replace
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
110
 remove
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 isInScope
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 isElementInScope
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 isOneOfSetInScope
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 isInListScope
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 isInButtonScope
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 isInTableScope
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 isInSelectScope
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 item
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 length
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 hasTemplate
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 dump
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 scopeDump
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\RemexHtml\TreeBuilder;
5
6use Wikimedia\RemexHtml\HTMLData;
7
8/**
9 * An implementation of the "stack of open elements" which includes a cache of
10 * elements currently in the various kinds of scope. It presumably has good
11 * worst-case performance at the expense of somewhat slower updates.
12 */
13class CachingStack extends Stack {
14    private const SCOPE_DEFAULT = 0;
15    private const SCOPE_LIST = 1;
16    private const SCOPE_BUTTON = 2;
17    private const SCOPE_TABLE = 3;
18    private const SCOPE_SELECT = 4;
19
20    private const ALL_SCOPES = [ self::SCOPE_DEFAULT, self::SCOPE_LIST, self::SCOPE_BUTTON,
21        self::SCOPE_TABLE, self::SCOPE_SELECT ];
22    private const NON_TABLE_SCOPES = [ self::SCOPE_DEFAULT, self::SCOPE_LIST, self::SCOPE_BUTTON,
23        self::SCOPE_SELECT ];
24    private const LIST_SCOPES = [ self::SCOPE_LIST, self::SCOPE_SELECT ];
25    private const BUTTON_SCOPES = [ self::SCOPE_BUTTON, self::SCOPE_SELECT ];
26    private const SELECT_ONLY = [ self::SCOPE_SELECT ];
27
28    private const MATH_BREAKERS = [
29        'mi' => true,
30        'mo' => true,
31        'mn' => true,
32        'ms' => true,
33        'mtext' => true,
34        'annotation-xml' => true
35    ];
36
37    private const SVG_BREAKERS = [
38        'foreignObject' => true,
39        'desc' => true,
40        'title' => true
41    ];
42
43    /**
44     * If you compile every predicate of the form "an X element in Y scope" in
45     * the HTML 5 spec, you discover that every element name X corresponds to
46     * at most one such scope Y. This is useful because it means when we see
47     * a new element, we need to add it to at most one scope cache.
48     *
49     * This is a list of such statements in the spec, and the scope they relate
50     * to. All formatting elements are included as SCOPE_DEFAULT since the AAA
51     * involves pulling an item out of the AFE list and checking if it is in
52     * scope.
53     */
54    private const PREDICATE_MAP = [
55        'a' => self::SCOPE_DEFAULT,
56        'address' => self::SCOPE_DEFAULT,
57        'applet' => self::SCOPE_DEFAULT,
58        'article' => self::SCOPE_DEFAULT,
59        'aside' => self::SCOPE_DEFAULT,
60        'b' => self::SCOPE_DEFAULT,
61        'big' => self::SCOPE_DEFAULT,
62        'blockquote' => self::SCOPE_DEFAULT,
63        'body' => self::SCOPE_DEFAULT,
64        'button' => self::SCOPE_DEFAULT,
65        'caption' => self::SCOPE_TABLE,
66        'center' => self::SCOPE_DEFAULT,
67        'code' => self::SCOPE_DEFAULT,
68        'dd' => self::SCOPE_DEFAULT,
69        'details' => self::SCOPE_DEFAULT,
70        'dialog' => self::SCOPE_DEFAULT,
71        'dir' => self::SCOPE_DEFAULT,
72        'div' => self::SCOPE_DEFAULT,
73        'dl' => self::SCOPE_DEFAULT,
74        'dt' => self::SCOPE_DEFAULT,
75        'em' => self::SCOPE_DEFAULT,
76        'fieldset' => self::SCOPE_DEFAULT,
77        'figcaption' => self::SCOPE_DEFAULT,
78        'figure' => self::SCOPE_DEFAULT,
79        'font' => self::SCOPE_DEFAULT,
80        'footer' => self::SCOPE_DEFAULT,
81        'form' => self::SCOPE_DEFAULT,
82        'h1' => self::SCOPE_DEFAULT,
83        'h2' => self::SCOPE_DEFAULT,
84        'h3' => self::SCOPE_DEFAULT,
85        'h4' => self::SCOPE_DEFAULT,
86        'h5' => self::SCOPE_DEFAULT,
87        'h6' => self::SCOPE_DEFAULT,
88        'header' => self::SCOPE_DEFAULT,
89        'hgroup' => self::SCOPE_DEFAULT,
90        'i' => self::SCOPE_DEFAULT,
91        'li' => self::SCOPE_LIST,
92        'listing' => self::SCOPE_DEFAULT,
93        'main' => self::SCOPE_DEFAULT,
94        'marquee' => self::SCOPE_DEFAULT,
95        'menu' => self::SCOPE_DEFAULT,
96        'nav' => self::SCOPE_DEFAULT,
97        'nobr' => self::SCOPE_DEFAULT,
98        'object' => self::SCOPE_DEFAULT,
99        'ol' => self::SCOPE_DEFAULT,
100        'p' => self::SCOPE_BUTTON,
101        'pre' => self::SCOPE_DEFAULT,
102        'ruby' => self::SCOPE_DEFAULT,
103        's' => self::SCOPE_DEFAULT,
104        'section' => self::SCOPE_DEFAULT,
105        'select' => self::SCOPE_SELECT,
106        'small' => self::SCOPE_DEFAULT,
107        'strike' => self::SCOPE_DEFAULT,
108        'strong' => self::SCOPE_DEFAULT,
109        'summary' => self::SCOPE_DEFAULT,
110        'table' => self::SCOPE_TABLE,
111        'tbody' => self::SCOPE_TABLE,
112        'td' => self::SCOPE_TABLE,
113        'tfoot' => self::SCOPE_TABLE,
114        'th' => self::SCOPE_TABLE,
115        'thead' => self::SCOPE_TABLE,
116        'tr' => self::SCOPE_TABLE,
117        'tt' => self::SCOPE_DEFAULT,
118        'u' => self::SCOPE_DEFAULT,
119        'ul' => self::SCOPE_DEFAULT,
120    ];
121
122    /**
123     * The stack of open elements
124     *
125     * @var array
126     */
127    private $elements = [];
128
129    /**
130     * A cache of the elements which are currently in a given scope.
131     * The first key is the scope ID, the second key is the element name, and the
132     * value is the first Element in a singly-linked list of Element objects,
133     * linked by $element->nextEltInScope.
134     *
135     * @todo Benchmark time and memory compared to an array stack instead of an
136     * SLL. The SLL here is maybe not quite so well justified as some other
137     * SLLs in RemexHtml.
138     *
139     * @var array<int,array<string,Element>>
140     */
141    private $scopes = [
142        self::SCOPE_DEFAULT => [],
143        self::SCOPE_LIST => [],
144        self::SCOPE_BUTTON => [],
145        self::SCOPE_TABLE => [],
146        self::SCOPE_SELECT => []
147    ];
148
149    /**
150     * This is the part of the scope cache which stores scope lists for objects
151     * which are not currently in scope. The first key is the scope ID, the
152     * second key is the stack index, the third key is the element name,
153     * and the value is the Element object.
154     *
155     * @var array<int,array<int,array<string,Element>>>
156     */
157    private $scopeStacks = [
158        self::SCOPE_DEFAULT => [],
159        self::SCOPE_LIST => [],
160        self::SCOPE_BUTTON => [],
161        self::SCOPE_TABLE => [],
162        self::SCOPE_SELECT => []
163    ];
164
165    /**
166     * The number of <template> elements in the stack of open elements. This
167     * speeds up the hot function hasTemplate().
168     *
169     * @var int
170     */
171    private $templateCount;
172
173    /**
174     * For a given namespace and element name, get the list of scopes
175     * for which a new scope should be created and the old one needs to
176     * be pushed onto the scope stack.
177     *
178     * @param string $ns
179     * @param string $name
180     * @return int[]
181     */
182    private function getScopeTypesToStack( $ns, $name ) {
183        if ( $ns === HTMLData::NS_HTML ) {
184            switch ( $name ) {
185                case 'html':
186                case 'table':
187                case 'template':
188                    return self::ALL_SCOPES;
189
190                case 'applet':
191                case 'caption':
192                case 'td':
193                case 'th':
194                case 'marquee':
195                case 'object':
196                    return self::NON_TABLE_SCOPES;
197
198                case 'ol':
199                case 'ul':
200                    return self::LIST_SCOPES;
201
202                case 'button':
203                    return self::BUTTON_SCOPES;
204
205                case 'option':
206                case 'optgroup':
207                    return [];
208
209                default:
210                    return self::SELECT_ONLY;
211            }
212        } elseif ( $ns === HTMLData::NS_MATHML ) {
213            if ( isset( self::MATH_BREAKERS[$name] ) ) {
214                return self::NON_TABLE_SCOPES;
215            } else {
216                return self::SELECT_ONLY;
217            }
218        } elseif ( $ns === HTMLData::NS_SVG ) {
219            if ( isset( self::SVG_BREAKERS[$name] ) ) {
220                return self::NON_TABLE_SCOPES;
221            } else {
222                return self::SELECT_ONLY;
223            }
224        } else {
225            return self::SELECT_ONLY;
226        }
227    }
228
229    /** @inheritDoc */
230    public function push( Element $elt ) {
231        // Update the stack store
232        $this->elements[] = $elt;
233        // Update the current node and index cache
234        $this->current = $elt;
235        $elt->stackIndex = array_key_last( $this->elements );
236        // Update the scope cache
237        $ns = $elt->namespace;
238        $name = $elt->name;
239        foreach ( $this->getScopeTypesToStack( $ns, $name ) as $type ) {
240            $this->scopeStacks[$type][] = $this->scopes[$type];
241            $this->scopes[$type] = [];
242        }
243        if ( $ns === HTMLData::NS_HTML && isset( self::PREDICATE_MAP[$name] ) ) {
244            $type = self::PREDICATE_MAP[$name];
245            $scope =& $this->scopes[$type];
246            $elt->nextEltInScope = $scope[$name] ?? null;
247            $scope[$name] = $elt;
248            unset( $scope );
249        }
250        // Update the template count
251        if ( $ns === HTMLData::NS_HTML && $name === 'template' ) {
252            $this->templateCount++;
253        }
254    }
255
256    /** @inheritDoc */
257    public function pop() {
258        if ( !$this->elements ) {
259            throw new TreeBuilderError( __METHOD__ . ': stack empty' );
260        }
261        // Update the stack store, index cache and current node
262        $elt = array_pop( $this->elements );
263        $elt->stackIndex = null;
264        $ns = $elt->namespace;
265        $name = $elt->name;
266        $this->current = array_last( $this->elements );
267        // Update the scope cache
268        if ( $ns === HTMLData::NS_HTML && isset( self::PREDICATE_MAP[$name] ) ) {
269            $scope = self::PREDICATE_MAP[$name];
270            $this->scopes[$scope][$name] = $elt->nextEltInScope;
271            $elt->nextEltInScope = null;
272        }
273        foreach ( $this->getScopeTypesToStack( $ns, $name ) as $scope ) {
274            $this->scopes[$scope] = array_pop( $this->scopeStacks[$scope] );
275        }
276        // Update the template count
277        if ( $ns === HTMLData::NS_HTML && $name === 'template' ) {
278            $this->templateCount--;
279        }
280        return $elt;
281    }
282
283    /** @inheritDoc */
284    public function replace( Element $oldElt, Element $elt ) {
285        $idx = $oldElt->stackIndex;
286        // AAA calls this function only for elements with the same name, which
287        // simplifies the scope cache update, and eliminates the template count
288        // update
289        if ( $oldElt->name !== $elt->name || $oldElt->namespace !== $elt->namespace ) {
290            throw new TreeBuilderError( __METHOD__ . ' can only be called for elements of the same name' );
291        }
292        $ns = $elt->namespace;
293        $name = $elt->name;
294        // Find the old element in its scope list and replace it
295        if ( $ns === HTMLData::NS_HTML && isset( self::PREDICATE_MAP[$name] ) ) {
296            $type = self::PREDICATE_MAP[$name];
297            $scopeElt = $this->scopes[$type][$name];
298            if ( $scopeElt === $oldElt ) {
299                $this->scopes[$type][$name] = $elt;
300                $elt->nextEltInScope = $scopeElt->nextEltInScope;
301                $scopeElt->nextEltInScope = null;
302            } else {
303                $nextElt = $scopeElt->nextEltInScope;
304                while ( $nextElt ) {
305                    if ( $nextElt === $oldElt ) {
306                        $scopeElt->nextEltInScope = $elt;
307                        $elt->nextEltInScope = $nextElt->nextEltInScope;
308                        $nextElt->nextEltInScope = null;
309                        break;
310                    }
311                    $scopeElt = $scopeElt->nextEltInScope;
312                    $nextElt = $scopeElt->nextEltInScope;
313                }
314                if ( !$nextElt ) {
315                    throw new TreeBuilderError( __METHOD__ . ': cannot find old element in scope cache' );
316                }
317            }
318        }
319        // Replace the stack element
320        $this->elements[$idx] = $elt;
321        if ( $idx === array_key_last( $this->elements ) ) {
322            $this->current = $elt;
323        }
324        $oldElt->stackIndex = null;
325        $elt->stackIndex = $idx;
326    }
327
328    /** @inheritDoc */
329    public function remove( Element $elt ) {
330        $tempStack = [];
331        $eltIndex = $elt->stackIndex;
332        if ( $eltIndex === null ) {
333            throw new TreeBuilderError( __METHOD__ . ': element not in stack' );
334        }
335        $n = count( $this->elements );
336        for ( $i = $n - 1; $i > $eltIndex; $i-- ) {
337            $tempStack[] = $this->pop();
338        }
339        $this->pop();
340        foreach ( array_reverse( $tempStack ) as $temp ) {
341            $this->push( $temp );
342        }
343    }
344
345    /** @inheritDoc */
346    public function isInScope( $name ) {
347        if ( self::PREDICATE_MAP[$name] !== self::SCOPE_DEFAULT ) {
348            throw new TreeBuilderError( "Unexpected predicate: \"$name is in scope\"" );
349        }
350        return !empty( $this->scopes[self::SCOPE_DEFAULT][$name] );
351    }
352
353    /** @inheritDoc */
354    public function isElementInScope( Element $elt ) {
355        $name = $elt->name;
356        if ( self::PREDICATE_MAP[$name] !== self::SCOPE_DEFAULT ) {
357            throw new TreeBuilderError( "Unexpected predicate: \"$name is in scope\"" );
358        }
359        if ( !empty( $this->scopes[self::SCOPE_DEFAULT][$name] ) ) {
360            $scopeMember = $this->scopes[self::SCOPE_DEFAULT][$name];
361            while ( $scopeMember ) {
362                if ( $scopeMember === $elt ) {
363                    return true;
364                }
365                $scopeMember = $scopeMember->nextEltInScope;
366            }
367        }
368        return false;
369    }
370
371    /** @inheritDoc */
372    public function isOneOfSetInScope( $names ) {
373        foreach ( $names as $name => $unused ) {
374            if ( $this->isInScope( $name ) ) {
375                return true;
376            }
377        }
378        return false;
379    }
380
381    /** @inheritDoc */
382    public function isInListScope( $name ) {
383        if ( self::PREDICATE_MAP[$name] !== self::SCOPE_LIST ) {
384            throw new TreeBuilderError( "Unexpected predicate: \"$name is in list scope\"" );
385        }
386        return !empty( $this->scopes[self::SCOPE_LIST][$name] );
387    }
388
389    /** @inheritDoc */
390    public function isInButtonScope( $name ) {
391        if ( self::PREDICATE_MAP[$name] !== self::SCOPE_BUTTON ) {
392            throw new TreeBuilderError( "Unexpected predicate: \"$name is in button scope\"" );
393        }
394        return !empty( $this->scopes[self::SCOPE_BUTTON][$name] );
395    }
396
397    /** @inheritDoc */
398    public function isInTableScope( $name ) {
399        if ( self::PREDICATE_MAP[$name] !== self::SCOPE_TABLE ) {
400            throw new TreeBuilderError( "Unexpected predicate: \"$name is in table scope\"" );
401        }
402        return !empty( $this->scopes[self::SCOPE_TABLE][$name] );
403    }
404
405    /** @inheritDoc */
406    public function isInSelectScope( $name ) {
407        if ( self::PREDICATE_MAP[$name] !== self::SCOPE_SELECT ) {
408            throw new TreeBuilderError( "Unexpected predicate: \"$name is in select scope\"" );
409        }
410        return !empty( $this->scopes[self::SCOPE_SELECT][$name] );
411    }
412
413    /** @inheritDoc */
414    public function item( $idx ) {
415        return $this->elements[$idx];
416    }
417
418    /** @inheritDoc */
419    public function length() {
420        return count( $this->elements );
421    }
422
423    /** @inheritDoc */
424    public function hasTemplate() {
425        return (bool)$this->templateCount;
426    }
427
428    /** @inheritDoc */
429    public function dump() {
430        return parent::dump() .
431            $this->scopeDump( self::SCOPE_DEFAULT, 'In scope' ) .
432            $this->scopeDump( self::SCOPE_LIST, 'In list scope' ) .
433            $this->scopeDump( self::SCOPE_BUTTON, 'In button scope' ) .
434            $this->scopeDump( self::SCOPE_TABLE, 'In table scope' ) .
435            $this->scopeDump( self::SCOPE_SELECT, 'In select scope' ) . "\n";
436    }
437
438    private function scopeDump( int $type, string $scopeName ): string {
439        if ( $this->scopes[$type] ) {
440            return "$scopeName: " . implode( ', ', array_keys( $this->scopes[$type] ) ) . "\n";
441        } else {
442            return '';
443        }
444    }
445}