Completed
Push — master ( d7961a...ff916f )
by Asmir
16:38 queued 12s
created

DOMTreeBuilder::eof()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Masterminds\HTML5\Parser;
4
5
use Masterminds\HTML5\Elements;
6
use Masterminds\HTML5\InstructionProcessor;
7
8
/**
9
 * Create an HTML5 DOM tree from events.
10
 *
11
 * This attempts to create a DOM from events emitted by a parser. This
12
 * attempts (but does not guarantee) to up-convert older HTML documents
13
 * to HTML5. It does this by applying HTML5's rules, but it will not
14
 * change the architecture of the document itself.
15
 *
16
 * Many of the error correction and quirks features suggested in the specification
17
 * are implemented herein; however, not all of them are. Since we do not
18
 * assume a graphical user agent, no presentation-specific logic is conducted
19
 * during tree building.
20
 *
21
 * FIXME: The present tree builder does not exactly follow the state machine rules
22
 * for insert modes as outlined in the HTML5 spec. The processor needs to be
23
 * re-written to accomodate this. See, for example, the Go language HTML5
24
 * parser.
25
 */
26
class DOMTreeBuilder implements EventHandler
27
{
28
    /**
29
     * Defined in http://www.w3.org/TR/html51/infrastructure.html#html-namespace-0.
30
     */
31
    const NAMESPACE_HTML = 'http://www.w3.org/1999/xhtml';
32
33
    const NAMESPACE_MATHML = 'http://www.w3.org/1998/Math/MathML';
34
35
    const NAMESPACE_SVG = 'http://www.w3.org/2000/svg';
36
37
    const NAMESPACE_XLINK = 'http://www.w3.org/1999/xlink';
38
39
    const NAMESPACE_XML = 'http://www.w3.org/XML/1998/namespace';
40
41
    const NAMESPACE_XMLNS = 'http://www.w3.org/2000/xmlns/';
42
43
    const OPT_DISABLE_HTML_NS = 'disable_html_ns';
44
45
    const OPT_TARGET_DOC = 'target_document';
46
47
    const OPT_IMPLICIT_NS = 'implicit_namespaces';
48
49
    /**
50
     * Holds the HTML5 element names that causes a namespace switch.
51
     *
52
     * @var array
53
     */
54
    protected $nsRoots = array(
55
        'html' => self::NAMESPACE_HTML,
56
        'svg' => self::NAMESPACE_SVG,
57
        'math' => self::NAMESPACE_MATHML,
58
    );
59
60
    /**
61
     * Holds the always available namespaces (which does not require the XMLNS declaration).
62
     *
63
     * @var array
64
     */
65
    protected $implicitNamespaces = array(
66
        'xml' => self::NAMESPACE_XML,
67
        'xmlns' => self::NAMESPACE_XMLNS,
68
        'xlink' => self::NAMESPACE_XLINK,
69
    );
70
71
    /**
72
     * Holds a stack of currently active namespaces.
73
     *
74
     * @var array
75
     */
76
    protected $nsStack = array();
77
78
    /**
79
     * Holds the number of namespaces declared by a node.
80
     *
81
     * @var array
82
     */
83
    protected $pushes = array();
84
85
    /**
86
     * Defined in 8.2.5.
87
     */
88
    const IM_INITIAL = 0;
89
90
    const IM_BEFORE_HTML = 1;
91
92
    const IM_BEFORE_HEAD = 2;
93
94
    const IM_IN_HEAD = 3;
95
96
    const IM_IN_HEAD_NOSCRIPT = 4;
97
98
    const IM_AFTER_HEAD = 5;
99
100
    const IM_IN_BODY = 6;
101
102
    const IM_TEXT = 7;
103
104
    const IM_IN_TABLE = 8;
105
106
    const IM_IN_TABLE_TEXT = 9;
107
108
    const IM_IN_CAPTION = 10;
109
110
    const IM_IN_COLUMN_GROUP = 11;
111
112
    const IM_IN_TABLE_BODY = 12;
113
114
    const IM_IN_ROW = 13;
115
116
    const IM_IN_CELL = 14;
117
118
    const IM_IN_SELECT = 15;
119
120
    const IM_IN_SELECT_IN_TABLE = 16;
121
122
    const IM_AFTER_BODY = 17;
123
124
    const IM_IN_FRAMESET = 18;
125
126
    const IM_AFTER_FRAMESET = 19;
127
128
    const IM_AFTER_AFTER_BODY = 20;
129
130
    const IM_AFTER_AFTER_FRAMESET = 21;
131
132
    const IM_IN_SVG = 22;
133
134
    const IM_IN_MATHML = 23;
135
136
    protected $options = array();
137
138
    protected $stack = array();
139
140
    protected $current; // Pointer in the tag hierarchy.
141
    protected $rules;
142
    protected $doc;
143
144
    protected $frag;
145
146
    protected $processor;
147
148
    protected $insertMode = 0;
149
150
    /**
151
     * Track if we are in an element that allows only inline child nodes.
152
     *
153
     * @var string|null
154
     */
155
    protected $onlyInline;
156
157
    /**
158
     * Quirks mode is enabled by default.
159
     * Any document that is missing the DT will be considered to be in quirks mode.
160
     */
161
    protected $quirks = true;
162
163
    protected $errors = array();
164
165 114
    public function __construct($isFragment = false, array $options = array())
166
    {
167 114
        $this->options = $options;
168
169 114
        if (isset($options[self::OPT_TARGET_DOC])) {
170 1
            $this->doc = $options[self::OPT_TARGET_DOC];
171 1
        } else {
172 113
            $impl = new \DOMImplementation();
173
            // XXX:
174
            // Create the doctype. For now, we are always creating HTML5
175
            // documents, and attempting to up-convert any older DTDs to HTML5.
176 113
            $dt = $impl->createDocumentType('html');
177
            // $this->doc = \DOMImplementation::createDocument(NULL, 'html', $dt);
178 113
            $this->doc = $impl->createDocument(null, null, $dt);
179 113
            $this->doc->encoding = !empty($options['encoding']) ? $options['encoding'] : 'UTF-8';
180
        }
181
182 114
        $this->errors = array();
183
184 114
        $this->current = $this->doc; // ->documentElement;
185
186
        // Create a rules engine for tags.
187 114
        $this->rules = new TreeBuildingRules();
188
189 114
        $implicitNS = array();
190 114
        if (isset($this->options[self::OPT_IMPLICIT_NS])) {
191
            $implicitNS = $this->options[self::OPT_IMPLICIT_NS];
192 114
        } elseif (isset($this->options['implicitNamespaces'])) {
193 2
            $implicitNS = $this->options['implicitNamespaces'];
194 2
        }
195
196
        // Fill $nsStack with the defalut HTML5 namespaces, plus the "implicitNamespaces" array taken form $options
197 114
        array_unshift($this->nsStack, $implicitNS + array('' => self::NAMESPACE_HTML) + $this->implicitNamespaces);
198
199 114
        if ($isFragment) {
200 19
            $this->insertMode = static::IM_IN_BODY;
201 19
            $this->frag = $this->doc->createDocumentFragment();
202 19
            $this->current = $this->frag;
203 19
        }
204 114
    }
205
206
    /**
207
     * Get the document.
208
     */
209 103
    public function document()
210
    {
211 103
        return $this->doc;
212
    }
213
214
    /**
215
     * Get the DOM fragment for the body.
216
     *
217
     * This returns a DOMNodeList because a fragment may have zero or more
218
     * DOMNodes at its root.
219
     *
220
     * @see http://www.w3.org/TR/2012/CR-html5-20121217/syntax.html#concept-frag-parse-context
221
     *
222
     * @return \DOMDocumentFragment
223
     */
224 19
    public function fragment()
225
    {
226 19
        return $this->frag;
227
    }
228
229
    /**
230
     * Provide an instruction processor.
231
     *
232
     * This is used for handling Processor Instructions as they are
233
     * inserted. If omitted, PI's are inserted directly into the DOM tree.
234
     *
235
     * @param InstructionProcessor $proc
236
     */
237 1
    public function setInstructionProcessor(InstructionProcessor $proc)
238
    {
239 1
        $this->processor = $proc;
240 1
    }
241
242 97
    public function doctype($name, $idType = 0, $id = null, $quirks = false)
243
    {
244
        // This is used solely for setting quirks mode. Currently we don't
245
        // try to preserve the inbound DT. We convert it to HTML5.
246 97
        $this->quirks = $quirks;
247
248 97
        if ($this->insertMode > static::IM_INITIAL) {
249
            $this->parseError('Illegal placement of DOCTYPE tag. Ignoring: ' . $name);
250
251
            return;
252
        }
253
254 97
        $this->insertMode = static::IM_BEFORE_HTML;
255 97
    }
256
257
    /**
258
     * Process the start tag.
259
     *
260
     * @todo - XMLNS namespace handling (we need to parse, even if it's not valid)
261
     *       - XLink, MathML and SVG namespace handling
262
     *       - Omission rules: 8.1.2.4 Optional tags
263
     *
264
     * @param string $name
265
     * @param array  $attributes
266
     * @param bool   $selfClosing
267
     *
268
     * @return int
269
     */
270 109
    public function startTag($name, $attributes = array(), $selfClosing = false)
271
    {
272 109
        $lname = $this->normalizeTagName($name);
273
274
        // Make sure we have an html element.
275 109
        if (!$this->doc->documentElement && 'html' !== $name && !$this->frag) {
276 3
            $this->startTag('html');
277 3
        }
278
279
        // Set quirks mode if we're at IM_INITIAL with no doctype.
280 109
        if ($this->insertMode === static::IM_INITIAL) {
281 5
            $this->quirks = true;
282 5
            $this->parseError('No DOCTYPE specified.');
283 5
        }
284
285
        // SPECIAL TAG HANDLING:
286
        // Spec says do this, and "don't ask."
287
        // find the spec where this is defined... looks problematic
288 109
        if ('image' === $name && !($this->insertMode === static::IM_IN_SVG || $this->insertMode === static::IM_IN_MATHML)) {
289
            $name = 'img';
290
        }
291
292
        // Autoclose p tags where appropriate.
293 109
        if ($this->insertMode >= static::IM_IN_BODY && Elements::isA($name, Elements::AUTOCLOSE_P)) {
294 57
            $this->autoclose('p');
295 57
        }
296
297
        // Set insert mode:
298
        switch ($name) {
299 109
            case 'html':
300 102
                $this->insertMode = static::IM_BEFORE_HEAD;
301 102
                break;
302 103
            case 'head':
303 44
                if ($this->insertMode > static::IM_BEFORE_HEAD) {
304
                    $this->parseError('Unexpected head tag outside of head context.');
305
                } else {
306 44
                    $this->insertMode = static::IM_IN_HEAD;
307
                }
308 44
                break;
309 102
            case 'body':
310 87
                $this->insertMode = static::IM_IN_BODY;
311 87
                break;
312 96
            case 'svg':
313 8
                $this->insertMode = static::IM_IN_SVG;
314 8
                break;
315 96
            case 'math':
316 7
                $this->insertMode = static::IM_IN_MATHML;
317 7
                break;
318 93
            case 'noscript':
319 1
                if ($this->insertMode === static::IM_IN_HEAD) {
320 1
                    $this->insertMode = static::IM_IN_HEAD_NOSCRIPT;
321 1
                }
322 1
                break;
323
        }
324
325
        // Special case handling for SVG.
326 109
        if ($this->insertMode === static::IM_IN_SVG) {
327 8
            $lname = Elements::normalizeSvgElement($lname);
328 8
        }
329
330 109
        $pushes = 0;
331
        // when we found a tag thats appears inside $nsRoots, we have to switch the defalut namespace
332 109
        if (isset($this->nsRoots[$lname]) && $this->nsStack[0][''] !== $this->nsRoots[$lname]) {
333 15
            array_unshift($this->nsStack, array(
334 15
                '' => $this->nsRoots[$lname],
335 15
            ) + $this->nsStack[0]);
336 15
            ++$pushes;
337 15
        }
338 109
        $needsWorkaround = false;
339 109
        if (isset($this->options['xmlNamespaces']) && $this->options['xmlNamespaces']) {
340
            // when xmlNamespaces is true a and we found a 'xmlns' or 'xmlns:*' attribute, we should add a new item to the $nsStack
341 6
            foreach ($attributes as $aName => $aVal) {
342 5
                if ('xmlns' === $aName) {
343 3
                    $needsWorkaround = $aVal;
344 3
                    array_unshift($this->nsStack, array(
345 3
                        '' => $aVal,
346 3
                    ) + $this->nsStack[0]);
347 3
                    ++$pushes;
348 5
                } elseif ('xmlns' === (($pos = strpos($aName, ':')) ? substr($aName, 0, $pos) : '')) {
349 3
                    array_unshift($this->nsStack, array(
350 3
                        substr($aName, $pos + 1) => $aVal,
351 3
                    ) + $this->nsStack[0]);
352 3
                    ++$pushes;
353 3
                }
354 6
            }
355 6
        }
356
357 109
        if ($this->onlyInline && Elements::isA($lname, Elements::BLOCK_TAG)) {
358 2
            $this->autoclose($this->onlyInline);
359 2
            $this->onlyInline = null;
360 2
        }
361
362
        try {
363 109
            $prefix = ($pos = strpos($lname, ':')) ? substr($lname, 0, $pos) : '';
364
365 109
            if (false !== $needsWorkaround) {
366 3
                $xml = "<$lname xmlns=\"$needsWorkaround\" " . (strlen($prefix) && isset($this->nsStack[0][$prefix]) ? ("xmlns:$prefix=\"" . $this->nsStack[0][$prefix] . '"') : '') . '/>';
367
368 3
                $frag = new \DOMDocument('1.0', 'UTF-8');
369 3
                $frag->loadXML($xml);
370
371 3
                $ele = $this->doc->importNode($frag->documentElement, true);
372 3
            } else {
373 109
                if (!isset($this->nsStack[0][$prefix]) || ('' === $prefix && isset($this->options[self::OPT_DISABLE_HTML_NS]) && $this->options[self::OPT_DISABLE_HTML_NS])) {
374 2
                    $ele = $this->doc->createElement($lname);
375 2
                } else {
376 108
                    $ele = $this->doc->createElementNS($this->nsStack[0][$prefix], $lname);
377
                }
378
            }
379 109
        } catch (\DOMException $e) {
380
            $this->parseError("Illegal tag name: <$lname>. Replaced with <invalid>.");
381
            $ele = $this->doc->createElement('invalid');
382
        }
383
384 109
        if (Elements::isA($lname, Elements::BLOCK_ONLY_INLINE)) {
385 30
            $this->onlyInline = $lname;
386 30
        }
387
388
        // When we add some namespacess, we have to track them. Later, when "endElement" is invoked, we have to remove them.
389
        // When we are on a void tag, we do not need to care about namesapce nesting.
390 109
        if ($pushes > 0 && !Elements::isA($name, Elements::VOID_TAG)) {
391
            // PHP tends to free the memory used by DOM,
392
            // to avoid spl_object_hash collisions whe have to avoid garbage collection of $ele storing it into $pushes
393
            // see https://bugs.php.net/bug.php?id=67459
394 17
            $this->pushes[spl_object_hash($ele)] = array($pushes, $ele);
395 17
        }
396
397 109
        foreach ($attributes as $aName => $aVal) {
398
            // xmlns attributes can't be set
399 81
            if ('xmlns' === $aName) {
400 5
                continue;
401
            }
402
403 80
            if ($this->insertMode === static::IM_IN_SVG) {
404 8
                $aName = Elements::normalizeSvgAttribute($aName);
405 80
            } elseif ($this->insertMode === static::IM_IN_MATHML) {
406 4
                $aName = Elements::normalizeMathMlAttribute($aName);
407 4
            }
408
409
            try {
410 80
                $prefix = ($pos = strpos($aName, ':')) ? substr($aName, 0, $pos) : false;
411
412 80
                if ('xmlns' === $prefix) {
413 4
                    $ele->setAttributeNS(self::NAMESPACE_XMLNS, $aName, $aVal);
414 80
                } elseif (false !== $prefix && isset($this->nsStack[0][$prefix])) {
415 6
                    $ele->setAttributeNS($this->nsStack[0][$prefix], $aName, $aVal);
416 6
                } else {
417 77
                    $ele->setAttribute($aName, $aVal);
418
                }
419 80
            } catch (\DOMException $e) {
420
                $this->parseError("Illegal attribute name for tag $name. Ignoring: $aName");
421
                continue;
422
            }
423
424
            // This is necessary on a non-DTD schema, like HTML5.
425 80
            if ('id' === $aName) {
426 24
                $ele->setIdAttribute('id', true);
427 24
            }
428 109
        }
429
430 109
        if ($this->frag !== $this->current && $this->rules->hasRules($name)) {
431
            // Some elements have special processing rules. Handle those separately.
432 6
            $this->current = $this->rules->evaluate($ele, $this->current);
433 6
        } else {
434
            // Otherwise, it's a standard element.
435 109
            $this->current->appendChild($ele);
436
437 109
            if (!Elements::isA($name, Elements::VOID_TAG)) {
438 109
                $this->current = $ele;
439 109
            }
440
441
            // Self-closing tags should only be respected on foreign elements
442
            // (and are implied on void elements)
443
            // See: https://www.w3.org/TR/html5/syntax.html#start-tags
444 109
            if (Elements::isHtml5Element($name)) {
445 108
                $selfClosing = false;
446 108
            }
447
        }
448
449
        // This is sort of a last-ditch attempt to correct for cases where no head/body
450
        // elements are provided.
451 109
        if ($this->insertMode <= static::IM_BEFORE_HEAD && 'head' !== $name && 'html' !== $name) {
452 5
            $this->insertMode = static::IM_IN_BODY;
453 5
        }
454
455
        // When we are on a void tag, we do not need to care about namesapce nesting,
456
        // but we have to remove the namespaces pushed to $nsStack.
457 109
        if ($pushes > 0 && Elements::isA($name, Elements::VOID_TAG)) {
458
            // remove the namespaced definded by current node
459
            for ($i = 0; $i < $pushes; ++$i) {
460
                array_shift($this->nsStack);
461
            }
462
        }
463
464 109
        if ($selfClosing) {
465 7
            $this->endTag($name);
466 7
        }
467
468
        // Return the element mask, which the tokenizer can then use to set
469
        // various processing rules.
470 109
        return Elements::element($name);
471
    }
472
473 107
    public function endTag($name)
474
    {
475 107
        $lname = $this->normalizeTagName($name);
476
477
        // Special case within 12.2.6.4.7: An end tag whose tag name is "br" should be treated as an opening tag
478 107
        if ($name === 'br') {
479 1
            $this->parseError('Closing tag encountered for void element br.');
480
481 1
            $this->startTag('br');
482 1
        }
483
        // Ignore closing tags for other unary elements.
484 107
        elseif (Elements::isA($name, Elements::VOID_TAG)) {
485
            return;
486
        }
487
488 107
        if ($this->insertMode <= static::IM_BEFORE_HTML) {
489
            // 8.2.5.4.2
490
            if (in_array($name, array(
491
                'html',
492
                'br',
493
                'head',
494
                'title',
495
            ))) {
496
                $this->startTag('html');
497
                $this->endTag($name);
498
                $this->insertMode = static::IM_BEFORE_HEAD;
499
500
                return;
501
            }
502
503
            // Ignore the tag.
504
            $this->parseError('Illegal closing tag at global scope.');
505
506
            return;
507
        }
508
509
        // Special case handling for SVG.
510 107
        if ($this->insertMode === static::IM_IN_SVG) {
511 8
            $lname = Elements::normalizeSvgElement($lname);
512 8
        }
513
514 107
        $cid = spl_object_hash($this->current);
515
516
        // XXX: HTML has no parent. What do we do, though,
517
        // if this element appears in the wrong place?
518 107
        if ('html' === $lname) {
519 98
            return;
520
        }
521
522
        // remove the namespaced definded by current node
523 101
        if (isset($this->pushes[$cid])) {
524 15
            for ($i = 0; $i < $this->pushes[$cid][0]; ++$i) {
525 15
                array_shift($this->nsStack);
526 15
            }
527 15
            unset($this->pushes[$cid]);
528 15
        }
529
530 101
        if (!$this->autoclose($lname)) {
531 3
            $this->parseError('Could not find closing tag for ' . $lname);
532 3
        }
533
534
        switch ($lname) {
535 101
            case 'head':
536 44
                $this->insertMode = static::IM_AFTER_HEAD;
537 44
                break;
538 100
            case 'body':
539 88
                $this->insertMode = static::IM_AFTER_BODY;
540 88
                break;
541 85
            case 'svg':
542 85
            case 'mathml':
543 8
                $this->insertMode = static::IM_IN_BODY;
544 8
                break;
545
        }
546 101
    }
547
548 5
    public function comment($cdata)
549
    {
550
        // TODO: Need to handle case where comment appears outside of the HTML tag.
551 5
        $node = $this->doc->createComment($cdata);
552 5
        $this->current->appendChild($node);
553 5
    }
554
555 91
    public function text($data)
556
    {
557
        // XXX: Hmmm.... should we really be this strict?
558 91
        if ($this->insertMode < static::IM_IN_HEAD) {
559
            // Per '8.2.5.4.3 The "before head" insertion mode' the characters
560
            // " \t\n\r\f" should be ignored but no mention of a parse error. This is
561
            // practical as most documents contain these characters. Other text is not
562
            // expected here so recording a parse error is necessary.
563 59
            $dataTmp = trim($data, " \t\n\r\f");
564 59
            if (!empty($dataTmp)) {
565
                // fprintf(STDOUT, "Unexpected insert mode: %d", $this->insertMode);
566 1
                $this->parseError('Unexpected text. Ignoring: ' . $dataTmp);
567 1
            }
568
569 59
            return;
570
        }
571
        // fprintf(STDOUT, "Appending text %s.", $data);
572 90
        $node = $this->doc->createTextNode($data);
573 90
        $this->current->appendChild($node);
574 90
    }
575
576 114
    public function eof()
577
    {
578
        // If the $current isn't the $root, do we need to do anything?
579 114
    }
580
581 13
    public function parseError($msg, $line = 0, $col = 0)
582
    {
583 13
        $this->errors[] = sprintf('Line %d, Col %d: %s', $line, $col, $msg);
584 13
    }
585
586 108
    public function getErrors()
587
    {
588 108
        return $this->errors;
589
    }
590
591 3
    public function cdata($data)
592
    {
593 3
        $node = $this->doc->createCDATASection($data);
594 3
        $this->current->appendChild($node);
595 3
    }
596
597 5
    public function processingInstruction($name, $data = null)
598
    {
599
        // XXX: Ignore initial XML declaration, per the spec.
600 5
        if ($this->insertMode === static::IM_INITIAL && 'xml' === strtolower($name)) {
601 1
            return;
602
        }
603
604
        // Important: The processor may modify the current DOM tree however it sees fit.
605 5
        if ($this->processor instanceof InstructionProcessor) {
606 1
            $res = $this->processor->process($this->current, $name, $data);
0 ignored issues
show
Bug introduced by
It seems like $this->current can also be of type object<DOMNode>; however, Masterminds\HTML5\InstructionProcessor::process() does only seem to accept object<DOMElement>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
607 1
            if (!empty($res)) {
608 1
                $this->current = $res;
609 1
            }
610
611 1
            return;
612
        }
613
614
        // Otherwise, this is just a dumb PI element.
615 4
        $node = $this->doc->createProcessingInstruction($name, $data);
616
617 4
        $this->current->appendChild($node);
618 4
    }
619
620
    // ==========================================================================
621
    // UTILITIES
622
    // ==========================================================================
623
624
    /**
625
     * Apply normalization rules to a tag name.
626
     * See sections 2.9 and 8.1.2.
627
     *
628
     * @param string $tagName
629
     *
630
     * @return string The normalized tag name.
631
     */
632 109
    protected function normalizeTagName($tagName)
633
    {
634
        /*
635
         * Section 2.9 suggests that we should not do this. if (strpos($name, ':') !== false) { // We know from the grammar that there must be at least one other // char besides :, since : is not a legal tag start. $parts = explode(':', $name); return array_pop($parts); }
636
         */
637 109
        return $tagName;
638
    }
639
640
    protected function quirksTreeResolver($name)
641
    {
642
        throw new \Exception('Not implemented.');
643
    }
644
645
    /**
646
     * Automatically climb the tree and close the closest node with the matching $tag.
647
     *
648
     * @param string $tagName
649
     *
650
     * @return bool
651
     */
652 101
    protected function autoclose($tagName)
653
    {
654 101
        $working = $this->current;
655
        do {
656 101
            if (XML_ELEMENT_NODE !== $working->nodeType) {
657 57
                return false;
658
            }
659 101
            if ($working->tagName === $tagName) {
660 101
                $this->current = $working->parentNode;
661
662 101
                return true;
663
            }
664 54
        } while ($working = $working->parentNode);
665
666
        return false;
667
    }
668
669
    /**
670
     * Checks if the given tagname is an ancestor of the present candidate.
671
     *
672
     * If $this->current or anything above $this->current matches the given tag
673
     * name, this returns true.
674
     *
675
     * @param string $tagName
676
     *
677
     * @return bool
678
     */
679
    protected function isAncestor($tagName)
680
    {
681
        $candidate = $this->current;
682
        while (XML_ELEMENT_NODE === $candidate->nodeType) {
683
            if ($candidate->tagName === $tagName) {
684
                return true;
685
            }
686
            $candidate = $candidate->parentNode;
687
        }
688
689
        return false;
690
    }
691
692
    /**
693
     * Returns true if the immediate parent element is of the given tagname.
694
     *
695
     * @param string $tagName
696
     *
697
     * @return bool
698
     */
699
    protected function isParent($tagName)
700
    {
701
        return $this->current->tagName === $tagName;
702
    }
703
}
704