Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 139
0.00% covered (danger)
0.00%
0 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dispatcher
0.00% covered (danger)
0.00%
0 / 139
0.00% covered (danger)
0.00%
0 / 18
5550
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
 switchMode
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 switchAndSave
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 restoreMode
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 getHandler
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isInTableMode
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 flushTableText
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 reset
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getAppropriateMode
0.00% covered (danger)
0.00%
0 / 52
0.00% covered (danger)
0.00%
0 / 1
702
 dispatcherCurrentNode
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
 startDocument
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
30
 endDocument
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 error
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 characters
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 startTag
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
156
 endTag
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 doctype
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 comment
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\RemexHtml\TreeBuilder;
5
6use Wikimedia\RemexHtml\HTMLData;
7use Wikimedia\RemexHtml\Tokenizer\Attributes;
8use Wikimedia\RemexHtml\Tokenizer\TokenHandler;
9use Wikimedia\RemexHtml\Tokenizer\Tokenizer;
10
11/**
12 * This is the approximate equivalent of the "tree construction dispatcher" in
13 * the spec. It receives token events and distributes them to the appropriate
14 * insertion mode class. It also implements some things specific to the
15 * dispatcher state:
16 *   - "Reset the insertion mode appropriately"
17 *   - The stack of template insertion modes
18 *   - The "original insertion mode"
19 */
20class Dispatcher implements TokenHandler {
21    /**
22     * The insertion mode indexes
23     */
24    public const INITIAL = 1;
25    public const BEFORE_HTML = 2;
26    public const BEFORE_HEAD = 3;
27    public const IN_HEAD = 4;
28    public const IN_HEAD_NOSCRIPT = 5;
29    public const AFTER_HEAD = 6;
30    public const IN_BODY = 7;
31    public const TEXT = 8;
32    public const IN_TABLE = 9;
33    public const IN_TABLE_TEXT = 10;
34    public const IN_CAPTION = 11;
35    public const IN_COLUMN_GROUP = 12;
36    public const IN_TABLE_BODY = 13;
37    public const IN_ROW = 14;
38    public const IN_CELL = 15;
39    public const IN_SELECT = 16;
40    public const IN_SELECT_IN_TABLE = 17;
41    public const IN_TEMPLATE = 18;
42    public const AFTER_BODY = 19;
43    public const IN_FRAMESET = 20;
44    public const AFTER_FRAMESET = 21;
45    public const AFTER_AFTER_BODY = 22;
46    public const AFTER_AFTER_FRAMESET = 23;
47    public const IN_FOREIGN_CONTENT = 24;
48    public const IN_PRE = 25;
49    public const IN_TEXTAREA = 26;
50
51    /**
52     * The handler class for each insertion mode
53     */
54    protected const HANDLER_CLASSES = [
55        self::INITIAL => Initial::class,
56        self::BEFORE_HTML => BeforeHtml::class,
57        self::BEFORE_HEAD => BeforeHead::class,
58        self::IN_HEAD => InHead::class,
59        self::IN_HEAD_NOSCRIPT => InHeadNoscript::class,
60        self::AFTER_HEAD => AfterHead::class,
61        self::IN_BODY => InBody::class,
62        self::TEXT => Text::class,
63        self::IN_TABLE => InTable::class,
64        self::IN_TABLE_TEXT => InTableText::class,
65        self::IN_CAPTION => InCaption::class,
66        self::IN_COLUMN_GROUP => InColumnGroup::class,
67        self::IN_TABLE_BODY => InTableBody::class,
68        self::IN_ROW => InRow::class,
69        self::IN_CELL => InCell::class,
70        self::IN_SELECT => InSelect::class,
71        self::IN_SELECT_IN_TABLE => InSelectInTable::class,
72        self::IN_TEMPLATE => InTemplate::class,
73        self::AFTER_BODY => AfterBody::class,
74        self::IN_FRAMESET => InFrameset::class,
75        self::AFTER_FRAMESET => AfterFrameset::class,
76        self::AFTER_AFTER_BODY => AfterAfterBody::class,
77        self::AFTER_AFTER_FRAMESET => AfterAfterFrameset::class,
78        self::IN_FOREIGN_CONTENT => InForeignContent::class,
79        self::IN_PRE => InPre::class,
80        self::IN_TEXTAREA => InTextarea::class,
81    ];
82
83    private const TABLE_MODES = [
84        self::IN_TABLE => true,
85        self::IN_CAPTION => true,
86        self::IN_TABLE_BODY => true,
87        self::IN_ROW => true,
88        self::IN_CELL => true,
89    ];
90
91    // Public shortcuts for "using the rules for" actions
92
93    /** @var InHead */
94    public $inHead;
95    /** @var InBody */
96    public $inBody;
97    /** @var InTable */
98    public $inTable;
99    /** @var InSelect */
100    public $inSelect;
101    /** @var InTemplate */
102    public $inTemplate;
103    /** @var InForeignContent */
104    public $inForeign;
105
106    protected TreeBuilder $builder;
107
108    /**
109     * The InsertionMode object for the current insertion mode in HTML content
110     *
111     * @var InsertionMode
112     */
113    protected $handler;
114
115    /**
116     * An array mapping insertion mode indexes to InsertionMode objects
117     *
118     * @var InsertionMode[]
119     */
120    protected $dispatchTable;
121
122    /**
123     * The insertion mode index
124     *
125     * @var int
126     */
127    protected $mode;
128
129    /**
130     * The "original insertion mode" index
131     *
132     * @var ?int
133     */
134    protected $originalMode;
135
136    /**
137     * The insertion mode sets this to true to acknowledge the tag's
138     * self-closing flag.
139     *
140     * @var bool|null
141     */
142    public $ack;
143
144    /**
145     * The stack of template insertion modes
146     */
147    public TemplateModeStack $templateModeStack;
148
149    /**
150     * @param TreeBuilder $builder
151     */
152    public function __construct( TreeBuilder $builder ) {
153        $this->builder = $builder;
154        $this->templateModeStack = new TemplateModeStack;
155    }
156
157    /**
158     * Switch the insertion mode, and return the new handler
159     *
160     * @param int $mode
161     * @return InsertionMode
162     */
163    public function switchMode( $mode ) {
164        $this->mode = $mode;
165        $this->handler = $this->dispatchTable[$mode];
166        return $this->handler;
167    }
168
169    /**
170     * Let the original insertion mode be the current insertion mode, and
171     * switch the insertion mode to some new value. Return the new handler.
172     *
173     * @param int $mode
174     * @return InsertionMode
175     */
176    public function switchAndSave( $mode ) {
177        $this->originalMode = $this->mode;
178        $this->mode = $mode;
179        $this->handler = $this->dispatchTable[$mode];
180        return $this->handler;
181    }
182
183    /**
184     * Switch the insertion mode to the original insertion mode and return the
185     * new handler.
186     *
187     * @return InsertionMode
188     */
189    public function restoreMode() {
190        if ( $this->originalMode === null ) {
191            throw new TreeBuilderError( "original insertion mode is not set" );
192        }
193        $mode = $this->mode = $this->originalMode;
194        $this->originalMode = null;
195        $this->handler = $this->dispatchTable[$mode];
196        return $this->handler;
197    }
198
199    /**
200     * Get the handler for the current insertion mode in HTML content.
201     * This is used by the "in foreign" handler to execute the HTML insertion
202     * mode. It does not necessarily correspond to the handler currently being
203     * executed.
204     *
205     * @return InsertionMode
206     */
207    public function getHandler() {
208        return $this->handler;
209    }
210
211    /**
212     * True if we are in a table mode, for the purposes of switching to
213     * IN_SELECT_IN_TABLE as opposed to IN_SELECT.
214     *
215     * @return bool
216     */
217    public function isInTableMode() {
218        return isset( self::TABLE_MODES[$this->mode] );
219    }
220
221    /**
222     * If the insertion mode is "in table text", flush the pending table text.
223     * This is a facility allowing users to insert into the DOM more cleanly.
224     */
225    public function flushTableText() {
226        if ( $this->mode === self::IN_TABLE_TEXT
227            && $this->handler instanceof InTableText
228        ) {
229            $this->handler->flush();
230        }
231    }
232
233    /**
234     * Reset the insertion mode appropriately, and return the new handler.
235     *
236     * @return InsertionMode
237     */
238    public function reset() {
239        return $this->switchMode( $this->getAppropriateMode() );
240    }
241
242    /**
243     * Get the insertion mode index which is switched to when we reset the
244     * insertion mode appropriately.
245     *
246     * @return int
247     */
248    protected function getAppropriateMode() {
249        $builder = $this->builder;
250        $stack = $builder->stack;
251        $last = false;
252        for ( $idx = $stack->length() - 1; $idx >= 0; $idx-- ) {
253            $node = $stack->item( $idx );
254            if ( $idx === 0 ) {
255                $last = true;
256                if ( $builder->isFragment ) {
257                    $node = $builder->fragmentContext;
258                }
259            }
260
261            switch ( $node->htmlName ) {
262                case 'select':
263                    if ( $last ) {
264                        return self::IN_SELECT;
265                    }
266                    for ( $ancestorIdx = $idx - 1; $ancestorIdx >= 1; $ancestorIdx-- ) {
267                        $ancestor = $stack->item( $ancestorIdx );
268                        if ( $ancestor->htmlName === 'template' ) {
269                            return self::IN_SELECT;
270                        } elseif ( $ancestor->htmlName === 'table' ) {
271                            return self::IN_SELECT_IN_TABLE;
272                        }
273                    }
274                    return self::IN_SELECT;
275
276                case 'td':
277                case 'th':
278                    if ( !$last ) {
279                        return self::IN_CELL;
280                    }
281                    break;
282
283                case 'tr':
284                    return self::IN_ROW;
285
286                case 'tbody':
287                case 'thead':
288                case 'tfoot':
289                    return self::IN_TABLE_BODY;
290
291                case 'caption':
292                    return self::IN_CAPTION;
293
294                case 'colgroup':
295                    return self::IN_COLUMN_GROUP;
296
297                case 'table':
298                    return self::IN_TABLE;
299
300                case 'template':
301                    return $this->templateModeStack->current;
302
303                case 'head':
304                    if ( $last ) {
305                        return self::IN_BODY;
306                    } else {
307                        return self::IN_HEAD;
308                    }
309
310                case 'body':
311                    return self::IN_BODY;
312
313                case 'frameset':
314                    return self::IN_FRAMESET;
315
316                case 'html':
317                    if ( $builder->headElement === null ) {
318                        return self::BEFORE_HEAD;
319                    } else {
320                        return self::AFTER_HEAD;
321                    }
322            }
323        }
324
325        return self::IN_BODY;
326    }
327
328    /**
329     * If the stack of open elements is empty, return null, otherwise return
330     * the adjusted current node.
331     * @return Element|null
332     */
333    protected function dispatcherCurrentNode() {
334        $current = $this->builder->stack->current;
335        if ( $current && $current->stackIndex === 0 && $this->builder->isFragment ) {
336            return $this->builder->fragmentContext;
337        } else {
338            return $current;
339        }
340    }
341
342    /** @inheritDoc */
343    public function startDocument( Tokenizer $tokenizer, $namespace, $name ) {
344        $this->dispatchTable = [];
345        foreach ( self::HANDLER_CLASSES as $mode => $class ) {
346            $this->dispatchTable[$mode] = new $class( $this->builder, $this );
347        }
348
349        $this->inHead = $this->dispatchTable[self::IN_HEAD];
350        $this->inBody = $this->dispatchTable[self::IN_BODY];
351        $this->inTable = $this->dispatchTable[self::IN_TABLE];
352        $this->inSelect = $this->dispatchTable[self::IN_SELECT];
353        $this->inTemplate = $this->dispatchTable[self::IN_TEMPLATE];
354        $this->inForeign = $this->dispatchTable[self::IN_FOREIGN_CONTENT];
355
356        $this->switchMode( self::INITIAL );
357
358        $this->builder->startDocument( $tokenizer, $namespace, $name );
359        if ( $namespace !== null ) {
360            if ( $namespace === HTMLData::NS_HTML && $name === 'template' ) {
361                $this->templateModeStack->push( self::IN_TEMPLATE );
362            }
363            $this->reset();
364        }
365    }
366
367    /**
368     * @inheritDoc
369     * @suppress PhanTypeMismatchPropertyProbablyReal Clears references to null
370     */
371    public function endDocument( $pos ) {
372        $this->handler->endDocument( $pos );
373
374        // All references to insertion modes must be explicitly released, since
375        // they have a circular reference back to $this
376        $this->dispatchTable = null;
377        $this->handler = null;
378        $this->inHead = null;
379        $this->inBody = null;
380        $this->inTable = null;
381        $this->inSelect = null;
382        $this->inTemplate = null;
383        $this->inForeign = null;
384    }
385
386    /** @inheritDoc */
387    public function error( $text, $pos ) {
388        $this->builder->error( $text, $pos );
389    }
390
391    /** @inheritDoc */
392    public function characters( $text, $start, $length, $sourceStart, $sourceLength ) {
393        $current = $this->dispatcherCurrentNode();
394        if ( !$current
395            || $current->namespace === HTMLData::NS_HTML
396            || $current->isMathmlTextIntegration()
397            || $current->isHtmlIntegration()
398        ) {
399            $this->handler->characters( $text, $start, $length, $sourceStart, $sourceLength );
400        } else {
401            $this->inForeign->characters(
402                $text, $start, $length, $sourceStart, $sourceLength );
403        }
404    }
405
406    /** @inheritDoc */
407    public function startTag( $name, Attributes $attrs, $selfClose, $sourceStart, $sourceLength ) {
408        $this->ack = false;
409        $current = $this->dispatcherCurrentNode();
410        if ( !$current
411            || $current->namespace === HTMLData::NS_HTML
412            || ( $current->isMathmlTextIntegration()
413                && $name !== 'mglyph'
414                && $name !== 'malignmark'
415            )
416            || ( $name === 'svg'
417                && $current->namespace === HTMLData::NS_MATHML
418                && $current->name === 'annotation-xml'
419            )
420            || $current->isHtmlIntegration()
421        ) {
422            $this->handler->startTag( $name, $attrs, $selfClose, $sourceStart, $sourceLength );
423        } else {
424            $this->inForeign->startTag( $name, $attrs, $selfClose, $sourceStart, $sourceLength );
425        }
426        if ( $selfClose && !$this->ack ) {
427            $this->builder->error( "unacknowledged self-closing tag", $sourceStart );
428        }
429    }
430
431    /** @inheritDoc */
432    public function endTag( $name, $sourceStart, $sourceLength ) {
433        $current = $this->dispatcherCurrentNode();
434        if ( !$current || $current->namespace === HTMLData::NS_HTML ) {
435            $this->handler->endTag( $name, $sourceStart, $sourceLength );
436        } else {
437            $this->inForeign->endTag( $name, $sourceStart, $sourceLength );
438        }
439    }
440
441    /** @inheritDoc */
442    public function doctype( $name, $public, $system, $quirks, $sourceStart, $sourceLength ) {
443        $current = $this->dispatcherCurrentNode();
444        if ( !$current || $current->namespace === HTMLData::NS_HTML ) {
445            $this->handler->doctype( $name, $public, $system, $quirks,
446                $sourceStart, $sourceLength );
447        } else {
448            $this->inForeign->doctype( $name, $public, $system, $quirks,
449                $sourceStart, $sourceLength );
450        }
451    }
452
453    /** @inheritDoc */
454    public function comment( $text, $sourceStart, $sourceLength ) {
455        $current = $this->dispatcherCurrentNode();
456        if ( !$current || $current->namespace === HTMLData::NS_HTML ) {
457            $this->handler->comment( $text, $sourceStart, $sourceLength );
458        } else {
459            $this->inForeign->comment( $text, $sourceStart, $sourceLength );
460        }
461    }
462}