Completed
Pull Request — master (#168)
by
unknown
07:12
created

DOMTreeBuilder::__construct()   B

Complexity

Conditions 6
Paths 18

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 6.0023

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 24
cts 25
cp 0.96
rs 8.6577
c 0
b 0
f 0
cc 6
nc 18
nop 2
crap 6.0023
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 112
    public function __construct($isFragment = false, array $options = array())
166
    {
167 112
        $this->options = $options;
168
169 112
        if (isset($options[self::OPT_TARGET_DOC])) {
170 1
            $this->doc = $options[self::OPT_TARGET_DOC];
171 1
        } else {
172 111
            $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 111
            $dt = $impl->createDocumentType('html');
177
            // $this->doc = \DOMImplementation::createDocument(NULL, 'html', $dt);
178 111
            $this->doc = $impl->createDocument(null, null, $dt);
179 111
            $this->doc->encoding = !empty($options['encoding']) ? $options['encoding'] : 'UTF-8';
180
        }
181
182 112
        $this->errors = array();
183
184 112
        $this->current = $this->doc; // ->documentElement;
185
186
        // Create a rules engine for tags.
187 112
        $this->rules = new TreeBuildingRules();
188
189 112
        $implicitNS = array();
190 112
        if (isset($this->options[self::OPT_IMPLICIT_NS])) {
191
            $implicitNS = $this->options[self::OPT_IMPLICIT_NS];
192 112
        } 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 112
        array_unshift($this->nsStack, $implicitNS + array('' => self::NAMESPACE_HTML) + $this->implicitNamespaces);
198
199 112
        if ($isFragment) {
200 18
            $this->insertMode = static::IM_IN_BODY;
201 18
            $this->frag = $this->doc->createDocumentFragment();
202 18
            $this->current = $this->frag;
203 18
        }
204 112
    }
205
206
    /**
207
     * Get the document.
208
     */
209 102
    public function document()
210
    {
211 102
        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 18
    public function fragment()
225
    {
226 18
        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 96
    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 96
        $this->quirks = $quirks;
247
248 96
        if ($this->insertMode > static::IM_INITIAL) {
249
            $this->parseError('Illegal placement of DOCTYPE tag. Ignoring: ' . $name);
250
251
            return;
252
        }
253
254 96
        $this->insertMode = static::IM_BEFORE_HTML;
255 96
    }
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 108
    public function startTag($name, $attributes = array(), $selfClosing = false)
271
    {
272 108
        $lname = $this->normalizeTagName($name);
273
274
        // Make sure we have an html element.
275 108
        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 108
        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 108
        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 108
        if ($this->insertMode >= static::IM_IN_BODY && Elements::isA($name, Elements::AUTOCLOSE_P)) {
294 56
            $this->autoclose('p');
295 56
        }
296
297
        // Set insert mode:
298
        switch ($name) {
299 108
            case 'html':
300 101
                $this->insertMode = static::IM_BEFORE_HEAD;
301 101
                break;
302 102
            case 'head':
303 43
                if ($this->insertMode > static::IM_BEFORE_HEAD) {
304
                    $this->parseError('Unexpected head tag outside of head context.');
305
                } else {
306 43
                    $this->insertMode = static::IM_IN_HEAD;
307
                }
308 43
                break;
309 101
            case 'body':
310 86
                $this->insertMode = static::IM_IN_BODY;
311 86
                break;
312 95
            case 'svg':
313 8
                $this->insertMode = static::IM_IN_SVG;
314 8
                break;
315 95
            case 'math':
316 7
                $this->insertMode = static::IM_IN_MATHML;
317 7
                break;
318 92
            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 108
        if ($this->insertMode === static::IM_IN_SVG) {
327 8
            $lname = Elements::normalizeSvgElement($lname);
328 8
        }
329
330 108
        $pushes = 0;
331
        // when we found a tag thats appears inside $nsRoots, we have to switch the defalut namespace
332 108
        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 108
        $needsWorkaround = false;
339 108
        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 108
        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 108
            $prefix = ($pos = strpos($lname, ':')) ? substr($lname, 0, $pos) : '';
364
365 108
            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 108
                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 107
                    $ele = $this->doc->createElementNS($this->nsStack[0][$prefix], $lname);
377
                }
378
            }
379 108
        } catch (\DOMException $e) {
380
            $this->parseError("Illegal tag name: <$lname>. Replaced with <invalid>.");
381
            $ele = $this->doc->createElement('invalid');
382
        }
383
384 108
        if (Elements::isA($lname, Elements::BLOCK_ONLY_INLINE)) {
385 29
            $this->onlyInline = $lname;
386 29
        }
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 108
        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 108
        foreach ($attributes as $aName => $aVal) {
398
            // xmlns attributes can't be set
399 80
            if ('xmlns' === $aName) {
400 5
                continue;
401
            }
402
403 79
            if ($this->insertMode === static::IM_IN_SVG) {
404 8
                $aName = Elements::normalizeSvgAttribute($aName);
405 79
            } elseif ($this->insertMode === static::IM_IN_MATHML) {
406 4
                $aName = Elements::normalizeMathMlAttribute($aName);
407 4
            }
408
409
            try {
410 79
                $prefix = ($pos = strpos($aName, ':')) ? substr($aName, 0, $pos) : false;
411
412 79
                if ('xmlns' === $prefix) {
413 4
                    $ele->setAttributeNS(self::NAMESPACE_XMLNS, $aName, $aVal);
414 79
                } elseif (false !== $prefix && isset($this->nsStack[0][$prefix])) {
415 6
                    $ele->setAttributeNS($this->nsStack[0][$prefix], $aName, $aVal);
416 6
                } else {
417 76
                    $ele->setAttribute($aName, $aVal);
418
                }
419 79
            } 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 79
            if ('id' === $aName) {
426 24
                $ele->setIdAttribute('id', true);
427 24
            }
428 108
        }
429
430 108
        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 108
            $this->current->appendChild($ele);
436
437 108
            if (!Elements::isA($name, Elements::VOID_TAG)) {
438 108
                $this->current = $ele;
439 108
            }
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 108
            if (Elements::isHtml5Element($name)) {
445 107
                $selfClosing = false;
446 107
            }
447
        }
448
449
        // This is sort of a last-ditch attempt to correct for cases where no head/body
450
        // elements are provided.
451 108
        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 108
        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 108
        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 108
        return Elements::element($name);
471
    }
472
473 106
    public function endTag($name)
474
    {
475 106
        $lname = $this->normalizeTagName($name);
476
477
        // Ignore closing tags for unary elements.
478 106
        if (Elements::isA($name, Elements::VOID_TAG)) {
479
            return;
480
        }
481
482 106
        if ($this->insertMode <= static::IM_BEFORE_HTML) {
483
            // 8.2.5.4.2
484
            if (in_array($name, array(
485
                'html',
486
                'br',
487
                'head',
488
                'title',
489
            ))) {
490
                $this->startTag('html');
491
                $this->endTag($name);
492
                $this->insertMode = static::IM_BEFORE_HEAD;
493
494
                return;
495
            }
496
497
            // Ignore the tag.
498
            $this->parseError('Illegal closing tag at global scope.');
499
500
            return;
501
        }
502
503
        // Special case handling for SVG.
504 106
        if ($this->insertMode === static::IM_IN_SVG) {
505 8
            $lname = Elements::normalizeSvgElement($lname);
506 8
        }
507
508 106
        $cid = spl_object_hash($this->current);
509
510
        // XXX: HTML has no parent. What do we do, though,
511
        // if this element appears in the wrong place?
512 106
        if ('html' === $lname) {
513 97
            return;
514
        }
515
516
        // remove the namespaced definded by current node
517 100
        if (isset($this->pushes[$cid])) {
518 15
            for ($i = 0; $i < $this->pushes[$cid][0]; ++$i) {
519 15
                array_shift($this->nsStack);
520 15
            }
521 15
            unset($this->pushes[$cid]);
522 15
        }
523
524 100
        if (!$this->autoclose($lname)) {
525 2
            $this->parseError('Could not find closing tag for ' . $lname);
526 2
        }
527
528
        switch ($lname) {
529 100
            case 'head':
530 43
                $this->insertMode = static::IM_AFTER_HEAD;
531 43
                break;
532 99
            case 'body':
533 87
                $this->insertMode = static::IM_AFTER_BODY;
534 87
                break;
535 84
            case 'svg':
536 84
            case 'mathml':
537 8
                $this->insertMode = static::IM_IN_BODY;
538 8
                break;
539
        }
540 100
    }
541
542 5
    public function comment($cdata)
543
    {
544
        // TODO: Need to handle case where comment appears outside of the HTML tag.
545 5
        $node = $this->doc->createComment($cdata);
546 5
        $this->current->appendChild($node);
547 5
    }
548
549 89
    public function text($data)
550
    {
551
        // XXX: Hmmm.... should we really be this strict?
552 89
        if ($this->insertMode < static::IM_IN_HEAD) {
553
            // Per '8.2.5.4.3 The "before head" insertion mode' the characters
554
            // " \t\n\r\f" should be ignored but no mention of a parse error. This is
555
            // practical as most documents contain these characters. Other text is not
556
            // expected here so recording a parse error is necessary.
557 58
            $dataTmp = trim($data, " \t\n\r\f");
558 58
            if (!empty($dataTmp)) {
559
                // fprintf(STDOUT, "Unexpected insert mode: %d", $this->insertMode);
560 1
                $this->parseError('Unexpected text. Ignoring: ' . $dataTmp);
561 1
            }
562
563 58
            return;
564
        }
565
        // fprintf(STDOUT, "Appending text %s.", $data);
566 88
        $node = $this->doc->createTextNode($data);
567 88
        $this->current->appendChild($node);
568 88
    }
569
570 112
    public function eof()
571
    {
572
        // If the $current isn't the $root, do we need to do anything?
573 112
    }
574
575 11
    public function parseError($msg, $line = 0, $col = 0)
576
    {
577 11
        $this->errors[] = sprintf('Line %d, Col %d: %s', $line, $col, $msg);
578 11
    }
579
580 106
    public function getErrors()
581
    {
582 106
        return $this->errors;
583
    }
584
585 3
    public function cdata($data)
586
    {
587 3
        $node = $this->doc->createCDATASection($data);
588 3
        $this->current->appendChild($node);
589 3
    }
590
591 5
    public function processingInstruction($name, $data = null)
592
    {
593
        // XXX: Ignore initial XML declaration, per the spec.
594 5
        if ($this->insertMode === static::IM_INITIAL && 'xml' === strtolower($name)) {
595 1
            return;
596
        }
597
598
        // Important: The processor may modify the current DOM tree however it sees fit.
599 5
        if ($this->processor instanceof InstructionProcessor) {
600 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...
601 1
            if (!empty($res)) {
602 1
                $this->current = $res;
603 1
            }
604
605 1
            return;
606
        }
607
608
        // Otherwise, this is just a dumb PI element.
609 4
        $node = $this->doc->createProcessingInstruction($name, $data);
610
611 4
        $this->current->appendChild($node);
612 4
    }
613
614
    // ==========================================================================
615
    // UTILITIES
616
    // ==========================================================================
617
618
    /**
619
     * Apply normalization rules to a tag name.
620
     * See sections 2.9 and 8.1.2.
621
     *
622
     * @param string $tagName
623
     *
624
     * @return string The normalized tag name.
625
     */
626 108
    protected function normalizeTagName($tagName)
627
    {
628
        /*
629
         * 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); }
630
         */
631 108
        return $tagName;
632
    }
633
634
    protected function quirksTreeResolver($name)
635
    {
636
        throw new \Exception('Not implemented.');
637
    }
638
639
    /**
640
     * Automatically climb the tree and close the closest node with the matching $tag.
641
     *
642
     * @param string $tagName
643
     *
644
     * @return bool
645
     */
646 100
    protected function autoclose($tagName)
647
    {
648 100
        $working = $this->current;
649
        do {
650 100
            if (XML_ELEMENT_NODE !== $working->nodeType) {
651 56
                return false;
652
            }
653 100
            if ($working->tagName === $tagName) {
654 100
                $this->current = $working->parentNode;
655
656 100
                return true;
657
            }
658 53
        } while ($working = $working->parentNode);
659
660
        return false;
661
    }
662
663
    /**
664
     * Checks if the given tagname is an ancestor of the present candidate.
665
     *
666
     * If $this->current or anything above $this->current matches the given tag
667
     * name, this returns true.
668
     *
669
     * @param string $tagName
670
     *
671
     * @return bool
672
     */
673
    protected function isAncestor($tagName)
674
    {
675
        $candidate = $this->current;
676
        while (XML_ELEMENT_NODE === $candidate->nodeType) {
677
            if ($candidate->tagName === $tagName) {
678
                return true;
679
            }
680
            $candidate = $candidate->parentNode;
681
        }
682
683
        return false;
684
    }
685
686
    /**
687
     * Returns true if the immediate parent element is of the given tagname.
688
     *
689
     * @param string $tagName
690
     *
691
     * @return bool
692
     */
693
    protected function isParent($tagName)
694
    {
695
        return $this->current->tagName === $tagName;
696
    }
697
}
698