Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
50.67% covered (warning)
50.67%
113 / 223
18.52% covered (danger)
18.52%
5 / 27
CRAP
0.00% covered (danger)
0.00%
0 / 1
DOMBuilder
50.67% covered (warning)
50.67%
113 / 223
18.52% covered (danger)
18.52%
5 / 27
1084.91
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
42
 rethrowIfNotDomException
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
4.94
 getFragment
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 isCoerced
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 startDocument
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 createDocument
71.43% covered (warning)
71.43%
15 / 21
0.00% covered (danger)
0.00%
0 / 1
13.82
 endDocument
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 insertNode
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
3.10
 maybeCoerce
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
5.39
 setAttribute
15.38% covered (danger)
15.38%
2 / 13
0.00% covered (danger)
0.00%
0 / 1
13.69
 createNode
83.87% covered (warning)
83.87%
26 / 31
0.00% covered (danger)
0.00%
0 / 1
17.07
 characters
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
56
 insertElement
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 endTag
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 doctype
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 comment
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 error
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 mergeAttributes
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 removeNode
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 reparentChildren
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 setAttributeWorkaround
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
5
 setAttributeNode
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 coerceName
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 parserDoctypeWorkaround
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 parserAttrWorkaround
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 parserElementWorkaround
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 parseHtml
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\RemexHtml\DOM;
5
6use Wikimedia\RemexHtml\HTMLData;
7use Wikimedia\RemexHtml\Tokenizer\Attribute;
8use Wikimedia\RemexHtml\Tokenizer\Attributes;
9use Wikimedia\RemexHtml\TreeBuilder\Element;
10use Wikimedia\RemexHtml\TreeBuilder\TreeBuilder;
11use Wikimedia\RemexHtml\TreeBuilder\TreeHandler;
12
13/**
14 * A TreeHandler which constructs a DOMDocument.
15 *
16 * Note that this class permits third-party `DOMImplementation`s
17 * (documents other than `\DOMDocument`, nodes other than `\DOMNode`,
18 * etc) and so no enforced PHP type hints are used which name these
19 * classes directly.  For the sake of static type checking, the
20 * types *in comments* are given as if the standard PHP `\DOM*`
21 * classes are being used but at runtime everything is duck-typed.
22 */
23class DOMBuilder implements TreeHandler {
24
25    /** @var string|null The name of the input document type */
26    public $doctypeName;
27
28    /** @var string|null The public ID */
29    public $public;
30
31    /** @var string|null The system ID */
32    public $system;
33
34    /**
35     * @var int The quirks mode. May be either TreeBuilder::NO_QUIRKS,
36     *   TreeBuilder::LIMITED_QUIRKS or TreeBuilder::QUIRKS to indicate
37     *   no-quirks mode, limited-quirks mode or quirks mode respectively.
38     */
39    public $quirks;
40
41    /** @var \DOMDocument */
42    private $doc;
43
44    /** @var callable|null */
45    private $errorCallback;
46
47    private bool $suppressHtmlNamespace;
48
49    private bool $createElementSetsNullNS;
50
51    private bool $suppressIdAttribute;
52
53    private bool $setAttributeWorkarounds;
54
55    /** @var string 'none', 'coerce', or 'parser' */
56    private string $coercionWorkaround;
57
58    /** @var callable(string):\DOMDocument */
59    private $htmlParser;
60
61    /** @var \DOMImplementation */
62    private $domImplementation;
63
64    /** @var class-string */
65    private $domExceptionClass;
66
67    /** @var bool */
68    private $isFragment;
69
70    /** @var bool */
71    private $coerced = false;
72
73    /**
74     * @param array $options An associative array of options:
75     *   - errorCallback : A function which is called on parse errors
76     *   - domImplementationClass : The string name of the DOMImplementation
77     *     class to use.  Defaults to `\DOMImplementation::class`; you can
78     *     pass `\Dom\Implementation::class` on PHP 8.4, or use a third-party
79     *     DOM implementation by passing an alternative class name here.
80     *   - domImplementation : The DOMImplementation object to use.  If this
81     *     parameter is missing or null, a new DOMImplementation object will
82     *     be constructed using the `domImplementationClass` option value.
83     *   - domExceptionClass : The string name of the DOMException
84     *     class to use.  Defaults to `\DOMException::class`; you can pass
85     *     `\Dom\Exception::class` on PHP 8.4, or use a third-party
86     *     DOM implementation by passing an alternative class name here.
87     *   - suppressHtmlNamespace : omit the namespace when creating HTML
88     *     elements. This corresponds to the PHP 8.4 `Dom\HTML_NO_DEFAULT_NS`
89     *     option to `Dom\HTMLDocument::createFromString()`.  This
90     *     defaults to `false` currently, but will default to `true`
91     *     when using `\DOMImplementation::class` in the next release.
92     *     Note that tag names with colons (like `<mw:section>`) won't
93     *     be properly parsed with `\DOMImplementation::class` unless
94     *     `suppressHtmlNamespace` is true, while the newer PHP 8.4
95     *     `\Dom\Implementation::class` will be forced to use a slow
96     *     workaround for tags containing colons if
97     *     `suppressHtmlNamespace` is `true`.
98     *   - suppressIdAttribute : don't call the nonstandard
99     *     `DOMElement::setIdAttribute()`/`Dom\Element::setIdAttribute()`
100     *     method while constructing elements.  False by default when using
101     *     `\DOMImplementation` or `\Dom\Implementation`, since this method
102     *     is needed for efficient `::getElementById()` calls in PHP.
103     *     Set to true if you are using a W3C spec-compliant DOM Implementation
104     *     and wish to avoid the use of nonstandard calls.
105     *   - coercionWorkaround : As discussed in T393922#10837089, the upstream
106     *     DOM spec allows fewer name characters for element, attribute, and
107     *     doctype names than permitted by the HTML parsing spec.  This option
108     *     can have the string value `'none'` which (re)throws a
109     *     DOMException when these characters are encountered during parsing,
110     *     or `'coerce'` to remap the names and set a flag; see
111     *     `::isCoerced()`.  A third option is to `'parser'` which will use
112     *     "another" HTML parser to create elements/attributes/doctypes with
113     *     the "illegal" names.  The default is to use `'parser'` in PHP 8.4+
114     *     and `'coerce'` otherwise.
115     *   - htmlParser: An optional callable with the signature
116     *     `string => Document`, used to implement the `'parser'` option to
117     *     `coercionWorkaround`, and also to create tags with names
118     *     containing colons when `suppressHtmlNamespace` is true and
119     *     `\Dom\Implementation::class` is used.  The default is `null`,
120     *     which uses `Dom\HTMLDocument::loadFromString` when available.
121     */
122    public function __construct( $options = [] ) {
123        $options += [
124            'errorCallback' => null,
125            'domImplementation' => null,
126            'domExceptionClass' => null,
127        ] + ( class_exists( '\Dom\Document' ) ? [
128            'domImplementationClass' => '\Dom\Implementation',
129        ] : [
130            'domImplementationClass' => \DOMImplementation::class,
131        ] );
132        $this->errorCallback = $options['errorCallback'];
133        $this->domImplementation = $options['domImplementation'] ??
134            new $options['domImplementationClass'];
135
136        $isOldNative = $this->domImplementation instanceof \DOMImplementation;
137        $isNewNative = is_a( $this->domImplementation, '\Dom\Implementation' );
138
139        $this->domExceptionClass = $options['domExceptionClass'] ??
140            ( $isNewNative ? '\Dom\Exception' : \DOMException::class );
141
142        $this->suppressHtmlNamespace = $options['suppressHtmlNamespace'] ??
143            $isOldNative;
144        $this->createElementSetsNullNS = $isOldNative;
145        $this->suppressIdAttribute = $options['suppressIdAttribute'] ??
146            !( $isOldNative || $isNewNative );
147        $this->setAttributeWorkarounds = $isOldNative;
148        if ( isset( $options['coercionWorkaround'] ) ) {
149            $this->coercionWorkaround = $options['coercionWorkaround'];
150        } elseif ( $isNewNative ) {
151            $this->coercionWorkaround = 'parser';
152        } else {
153            $this->coercionWorkaround = 'coerce';
154        }
155        $this->htmlParser = $options['htmlParser'] ?? null;
156    }
157
158    private function rethrowIfNotDomException( \Throwable $t ) {
159        if ( is_a( $t, $this->domExceptionClass, false ) ) {
160            return;
161        }
162        // PHP 8.4 claims to alias \Dom\Exception to \DOMException but
163        // is_a doesn't recognize the alias, so check both.
164        if ( is_a( $t, \DOMException::class, false ) ) {
165            return;
166        }
167        // @phan-suppress-next-line PhanThrowTypeAbsent
168        throw $t;
169    }
170
171    /**
172     * Get the constructed document or document fragment. In the fragment case,
173     * a DOMElement is returned, and the caller is expected to extract its
174     * inner contents, ignoring the wrapping element. This convention is
175     * convenient because the wrapping element gives libxml somewhere to put
176     * its namespace declarations. If we copied the children into a
177     * DOMDocumentFragment, libxml would invent new prefixes for the orphaned
178     * namespaces.
179     *
180     * @return \DOMNode
181     */
182    public function getFragment() {
183        if ( $this->isFragment ) {
184            return $this->doc->documentElement;
185        } else {
186            return $this->doc;
187        }
188    }
189
190    /**
191     * Returns true if the document was coerced due to libxml limitations. We
192     * follow HTML 5.1 § 8.2.7 "Coercing an HTML DOM into an infoset".
193     *
194     * @return bool
195     */
196    public function isCoerced() {
197        return $this->coerced;
198    }
199
200    /** @inheritDoc */
201    public function startDocument( $fragmentNamespace, $fragmentName ) {
202        $this->isFragment = $fragmentNamespace !== null;
203        $this->doc = $this->createDocument();
204    }
205
206    /**
207     * @param string|null $doctypeName
208     * @param string|null $public
209     * @param string|null $system
210     * @return \DOMDocument
211     * @suppress PhanTypeMismatchArgumentInternalReal
212     *   Null args to DOMImplementation::createDocument
213     */
214    protected function createDocument(
215        ?string $doctypeName = null,
216        ?string $public = null,
217        ?string $system = null
218    ) {
219        $impl = $this->domImplementation;
220        if ( $doctypeName === '' && $this->coercionWorkaround === 'coerce' ) {
221            $this->coerced = true;
222            $doc = $impl->createDocument( null, '' );
223        } elseif ( $doctypeName === null ) {
224            $doc = $impl->createDocument( null, '' );
225        } elseif (
226            $doctypeName === 'html' && ( !$public ) && ( !$system ) &&
227            method_exists( $impl, 'createHtmlDocument' )
228        ) {
229            // @phan-suppress-next-line PhanUndeclaredMethod
230            $doc = $impl->createHtmlDocument();
231            // Remove all nodes but the doctype node (the first)
232            while ( $doc->lastChild && $doc->lastChild->nodeType !== 10 ) {
233                $doc->removeChild( $doc->lastChild );
234            }
235        } else {
236            $doctype = $this->maybeCoerce(
237                $doctypeName,
238                static fn ( $name ) => $impl->createDocumentType( $doctypeName, $public ?? '', $system ?? '' ),
239                fn () => $this->parserDoctypeWorkaround( $doctypeName, $public ?? '', $system ?? '' )
240            );
241            $doc = $impl->createDocument( null, '', $doctype );
242        }
243        if ( $doc instanceof \DOMDocument ) {
244            $doc->encoding = 'UTF-8';
245        } else {
246            $doc->characterSet = 'UTF-8';
247        }
248        return $doc;
249    }
250
251    /** @inheritDoc */
252    public function endDocument( $pos ) {
253    }
254
255    /**
256     * @param int $preposition
257     * @param Element $refElement
258     * @param \DOMNode $node
259     */
260    protected function insertNode( $preposition, $refElement, $node ) {
261        if ( $preposition === TreeBuilder::ROOT ) {
262            $parent = $this->doc;
263            $refNode = null;
264        } elseif ( $preposition === TreeBuilder::BEFORE ) {
265            $parent = $refElement->userData->parentNode;
266            $refNode = $refElement->userData;
267        } else {
268            $parent = $refElement->userData;
269            $refNode = null;
270        }
271        $parent->insertBefore( $node, $refNode );
272    }
273
274    /**
275     * Helper function to try to execute a function, coercing the given
276     * name and trying again if it throws a DOMException.
277     *
278     * @template T
279     * @param string $name The name to possibly coerce
280     * @param callable(string):T $func The operation we wish to perform
281     * @param ?callable():T $parserWorkaround An alternative method to
282     *  perform this operation using an HTML parser.
283     * @return T returns the value returned by $func
284     */
285    private function maybeCoerce( string $name, callable $func, ?callable $parserWorkaround ) {
286        if ( $this->coercionWorkaround === 'none' ) {
287            return $func( $name );
288        }
289        try {
290            return $func( $name );
291        } catch ( \Throwable $e ) {
292            $this->rethrowIfNotDomException( $e );
293        }
294        if ( $this->coercionWorkaround === 'coerce' || $parserWorkaround === null ) {
295            return $func( $this->coerceName( $name ) );
296        }
297        // Alternative implementation using an HTML parser.
298        return $parserWorkaround();
299    }
300
301    /**
302     * Helper function to set the value of an attribute on the node,
303     * working around various PHP bugs in the process.
304     * @param \DOMElement $node
305     * @param Attribute $attr
306     * @param bool $needRetval Whether we need the previous value returned
307     * @return ?string The old value of the attribute
308     */
309    private function setAttribute( $node, Attribute $attr, bool $needRetval = false ): ?string {
310        if ( $this->setAttributeWorkarounds ) {
311            return $this->setAttributeWorkaround( $node, $attr, $needRetval );
312        }
313        return $this->maybeCoerce(
314            $attr->qualifiedName,
315            static function ( $name ) use ( $node, $attr, $needRetval ) {
316                $oldValue = $needRetval ? $node->getAttribute( $name ) : null;
317                if ( $attr->namespaceURI === null ) {
318                    $node->setAttribute( $name, $attr->value );
319                } else {
320                    $node->setAttributeNS( $attr->namespaceURI, $name, $attr->value );
321                }
322                return $oldValue;
323            },
324            fn () => $this->parserAttrWorkaround( $node, $attr )
325        );
326    }
327
328    /**
329     * @return \DOMNode
330     */
331    protected function createNode( Element $element ) {
332        $isHtmlNS = ( $element->namespace === HTMLData::NS_HTML );
333        if ( $this->createElementSetsNullNS ) {
334            $useCreateElement = $this->suppressHtmlNamespace && $isHtmlNS;
335            if ( str_contains( $element->name, ':' ) ) {
336                // With \DOMImplementation, we have to use createElement
337                // for elements with colons in their names, even though
338                // this will leave them with a null namespace.
339                $useCreateElement = true;
340            }
341        } elseif ( $this->suppressHtmlNamespace && $isHtmlNS ) {
342            $useCreateElement = false;
343        } else {
344            // Use createElement for HTML namespace elements, because otherwise
345            // the localName will get split on a ':' in $element->name.
346            $useCreateElement = $isHtmlNS;
347        }
348        if ( $useCreateElement ) {
349            $node = $this->maybeCoerce(
350                $element->name,
351                $this->doc->createElement( ... ),
352                fn () => $this->parserElementWorkaround( $element->name )
353            );
354        } elseif ( $this->createElementSetsNullNS || !str_contains( $element->name, ':' ) ) {
355            $namespace = ( $this->suppressHtmlNamespace && $isHtmlNS ) ? null :
356                $element->namespace;
357            $node = $this->maybeCoerce( $element->name, fn ( $name ) =>
358                $this->doc->createElementNS( $namespace, $name ),
359                null
360            );
361        } else {
362            $node = $this->parserElementWorkaround( $element->name );
363        }
364
365        foreach ( $element->attrs->getObjects() as $attr ) {
366            if ( $attr->namespaceURI === null &&
367                !preg_match( '/[^-A-Za-z]/S', $attr->qualifiedName )
368            ) {
369                // Fast path: no coercion or namespaces necessary
370                $node->setAttribute( $attr->qualifiedName, $attr->value );
371            } else {
372                $this->setAttribute( $node, $attr );
373            }
374        }
375        if ( ( !$this->suppressIdAttribute ) && $node->hasAttribute( 'id' ) ) {
376            // This is a call to a non-standard DOM method required by PHP in
377            // order to implement DOMDocument::getElementById() efficiently.
378            $node->setIdAttribute( 'id', true );
379        }
380        $element->userData = $node;
381        return $node;
382    }
383
384    /** @inheritDoc */
385    public function characters( $preposition, $refElement, $text, $start, $length,
386        $sourceStart, $sourceLength
387    ) {
388        // Parse $preposition and $refElement as in self::insertNode()
389        if ( $preposition === TreeBuilder::ROOT ) {
390            $parent = $this->doc;
391            $refNode = null;
392        } elseif ( $preposition === TreeBuilder::BEFORE ) {
393            $parent = $refElement->userData->parentNode;
394            $refNode = $refElement->userData;
395        } else {
396            $parent = $refElement->userData;
397            $refNode = null;
398        }
399        // https://html.spec.whatwg.org/#insert-a-character
400        // If the adjusted insertion location is in a Document node, then
401        // return.
402        if ( $parent === $this->doc ) {
403            return;
404        }
405        $data = substr( $text, $start, $length );
406        // If there is a Text node immediately before the adjusted insertion
407        // location, then append data to that Text node's data.
408        if ( $refNode === null ) {
409            $prev = $parent->lastChild;
410        } else {
411            /** @var \DOMNode $refNode */
412            $prev = $refNode->previousSibling;
413        }
414        if ( $prev !== null && $prev->nodeType === XML_TEXT_NODE ) {
415            '@phan-var \DOMCharacterData $prev'; /** @var \DOMCharacterData $prev */
416            $prev->appendData( $data );
417        } else {
418            $node = $this->doc->createTextNode( $data );
419            $this->insertNode( $preposition, $refElement, $node );
420        }
421    }
422
423    /** @inheritDoc */
424    public function insertElement( $preposition, $refElement, Element $element, $void,
425        $sourceStart, $sourceLength
426    ) {
427        if ( $element->userData ) {
428            $node = $element->userData;
429        } else {
430            $node = $this->createNode( $element );
431        }
432        $this->insertNode( $preposition, $refElement, $node );
433    }
434
435    /** @inheritDoc */
436    public function endTag( Element $element, $sourceStart, $sourceLength ) {
437    }
438
439    /** @inheritDoc */
440    public function doctype( $name, $public, $system, $quirks, $sourceStart, $sourceLength ) {
441        if ( !$this->doc->firstChild ) {
442            $this->doc = $this->createDocument( $name, $public, $system );
443        }
444        $this->doctypeName = $name;
445        $this->public = $public;
446        $this->system = $system;
447        $this->quirks = $quirks;
448    }
449
450    /** @inheritDoc */
451    public function comment( $preposition, $refElement, $text, $sourceStart, $sourceLength ) {
452        $node = $this->doc->createComment( $text );
453        $this->insertNode( $preposition, $refElement, $node );
454    }
455
456    /** @inheritDoc */
457    public function error( $text, $pos ) {
458        if ( $this->errorCallback ) {
459            ( $this->errorCallback )( $text, $pos );
460        }
461    }
462
463    /** @inheritDoc */
464    public function mergeAttributes( Element $element, Attributes $attrs, $sourceStart ) {
465        $node = $element->userData;
466        '@phan-var \DOMElement $node'; /** @var \DOMElement $node */
467        foreach ( $attrs->getObjects() as $name => $attr ) {
468            // As noted in createNode(), we can't use hasAttribute() reliably
469            // on some DOM implementations. However, we can use the return
470            // value (eg, of setAttributeNode()) to reliably tell us the
471            // *previous* value, and so we can use that to fix up the corner
472            // cases.
473            $oldValue = $this->setAttribute( $node, $attr, true );
474            if ( $oldValue !== null ) {
475                // Put it back how it was
476                $a = clone $attr;
477                $a->value = $oldValue;
478                $this->setAttribute( $node, $a );
479            }
480        }
481    }
482
483    /** @inheritDoc */
484    public function removeNode( Element $element, $sourceStart ) {
485        $node = $element->userData;
486        $node->parentNode->removeChild( $node );
487    }
488
489    /** @inheritDoc */
490    public function reparentChildren( Element $element, Element $newParent, $sourceStart ) {
491        $this->insertElement( TreeBuilder::UNDER, $element, $newParent, false, $sourceStart, 0 );
492        $node = $element->userData;
493        /** @var \DOMElement $newParentNode */
494        $newParentNode = $newParent->userData;
495        '@phan-var \DOMElement $newParentNode';
496        while ( $node->firstChild !== $newParentNode ) {
497            $firstChild = $node->firstChild;
498            '@phan-var \DOMNode $firstChild';
499            $newParentNode->appendChild( $firstChild );
500        }
501    }
502
503    // SetAttribute workarounds, for \DOMDocument
504
505    /**
506     * Implement various workarounds for ::setAttribute needed for
507     * \DOMDocument.
508     * @param \DOMElement $node
509     * @param Attribute $attr
510     * @param bool $needRetval
511     * @return ?string The previous value of the attribute, or null if none
512     */
513    private function setAttributeWorkaround( $node, Attribute $attr, bool $needRetval ): ?string {
514        if ( $attr->namespaceURI === null ) {
515            return $this->maybeCoerce(
516                $attr->localName,
517                fn ( $name ) => $this->setAttributeNode(
518                    $node,
519                    $this->doc->createAttribute( $name ),
520                    $attr->value
521                ),
522                fn () => $this->parserAttrWorkaround( $node, $attr )
523            );
524        } elseif ( $attr->qualifiedName === 'xmlns' ) {
525            # T235295: \DOMDocument treats 'xmlns' as special
526            $oldValue = $needRetval && $node->hasAttribute( $attr->qualifiedName ) ?
527                $node->getAttribute( $attr->qualifiedName ) : null;
528            $node->setAttributeNS(
529                $attr->namespaceURI, $attr->qualifiedName, $attr->value
530            );
531            return $oldValue;
532        } else {
533            return $this->maybeCoerce( $attr->qualifiedName, fn ( $name ) =>
534                $this->setAttributeNode(
535                    $node,
536                    $this->doc->createAttributeNS( $attr->namespaceURI, $name ),
537                    $attr->value
538                ),
539                fn () => $this->parserAttrWorkaround( $node, $attr )
540            );
541        }
542    }
543
544    /**
545     * Helper function to set an attribute from an attribute node object.
546     * @param \DOMElement $node
547     * @param \DOMAttr $attrNode
548     * @param string $value The desired attribute value
549     * @return ?string The old value of the attribute
550     */
551    private function setAttributeNode( $node, $attrNode, string $value ): ?string {
552        // FIXME: this apparently works to create a prefixed localName
553        // in the null namespace, but this is probably taking advantage
554        // of a bug in PHP's DOM library, and screws up in various
555        // interesting ways. For example, some attributes created in this
556        // way can't be discovered via hasAttribute() or hasAttributeNS().
557        if ( $this->domImplementation instanceof \DOMImplementation ) {
558            // This ::appendChild trick only works in broken DOM
559            // implementations! DOM standard says it should throw.
560            $attrNode->appendChild(
561                $this->doc->createTextNode( $value )
562            );
563        } else {
564            $attrNode->value = $value;
565        }
566        $old = $node->setAttributeNode( $attrNode );
567        return $old !== null ? $old->value : null;
568    }
569
570    // Name coercion workaround: remap name and set a flag
571
572    /**
573     * Replace unsupported characters with a code of the form U123456.
574     *
575     * @param string $name
576     * @return string
577     */
578    private function coerceName( $name ) {
579        $coercedName = DOMUtils::coerceName( $name );
580        if ( $name !== $coercedName ) {
581            $this->coerced = true;
582        }
583        return $coercedName;
584    }
585
586    // Name coercion workaround using an HTML parser
587
588    /**
589     * Use the PHP \Dom\HTMLDocument parser to create a doctype node which
590     * is impossible to create with DOM methods.
591     * @see https://github.com/whatwg/dom/issues/849#issuecomment-2877929861
592     * @param string $doctypeName
593     * @param string $public
594     * @param string $system
595     * @return \DOMDocumentType (or an implementation-defined type)
596     */
597    private function parserDoctypeWorkaround(
598        string $doctypeName, string $public, string $system
599    ) {
600        // If $doctypeName doesn't match the Name production or QName
601        // production a DOMException is thrown from
602        // ::createDocumentType() according to the spec:
603        // https://dom.spec.whatwg.org/#interface-domimplementation
604        // "Real" implementations add a DocumentType element anyway
605        // when parsing, but there is no standard DOM method which
606        // would allow us the create the invalid DocumentType which
607        // is typically used in this case.
608        $html = "<!DOCTYPE {$doctypeName} {$public} {$system}>";
609        $doc = $this->parseHtml( $html );
610        return $doc->doctype;
611    }
612
613    /**
614     * Use HTML parser to create an Attribute which is impossible to
615     * create using normal DOM methods.
616     * @see https://github.com/whatwg/dom/issues/769
617     * @param \DOMElement $node (or an implementation-defined type)
618     * @param Attribute $attr
619     * @return ?string The previous value of the given attribute
620     */
621    private function parserAttrWorkaround(
622        $node, Attribute $attr
623    ): ?string {
624        $html = "<div id=target><div {$attr->qualifiedName}=''></div></div>";
625        $doc = $this->parseHtml( $html );
626        // @phan-suppress-next-line PhanTypeArraySuspicious (works for \Dom\Element)
627        $a = $doc->getElementById( 'target' )->firstChild
628           ->attributes[0]->cloneNode( true );
629        $a = $this->doc->adoptNode( $a );
630        $a->value = $attr->value;
631        $oldNode = $node->setAttributeNode( $a );
632        return $oldNode !== null ? $oldNode->value : null;
633    }
634
635    /**
636     * Use HTML parser to create an Element which is impossible to
637     * create using normal DOM methods.
638     * @see https://github.com/whatwg/dom/issues/849
639     * @param string $name The tag name to create
640     * @return \DOMElement (or an implementation-defined type)
641     */
642    private function parserElementWorkaround( string $name ) {
643        $html = "<div id=target><{$name}>";
644        $doc = $this->parseHtml( $html );
645        $el = $doc->getElementById( 'target' )->firstChild;
646        '@phan-var \DOMElement $el';
647        return $this->doc->adoptNode( $el );
648    }
649
650    /**
651     * @param string $html
652     * @return \DOMDocument (or an implementation-defined type)
653     */
654    private function parseHtml( string $html ) {
655        if ( $this->htmlParser ) {
656            return ( $this->htmlParser )( $html );
657        } else {
658            $options = LIBXML_NOERROR |
659                ( $this->suppressHtmlNamespace ? constant( '\Dom\HTML_NO_DEFAULT_NS' ) : 0 );
660            $doc = \Dom\HTMLDocument::createFromString( $html, $options );
661            '@phan-var \DOMDocument $doc';
662            return $doc;
663        }
664    }
665
666}