Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.70% covered (success)
94.70%
268 / 283
81.48% covered (warning)
81.48%
22 / 27
CRAP
0.00% covered (danger)
0.00%
0 / 1
CommentUtils
94.70% covered (success)
94.70%
268 / 283
81.48% covered (warning)
81.48%
22 / 27
165.91
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isBlockElement
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 isRenderingTransparentNode
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
11
 isOurGeneratedNode
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 cantHaveElementChildren
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
7
 isCommentSeparator
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
13
 isCommentContent
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 childIndexOf
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 contains
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 closestElement
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 closestElementWithSibling
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
72
 getTranscludedFromElement
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
10
 getHeadlineNode
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
5.93
 htmlTrim
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getIndentLevel
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
6
 getCoveredSiblings
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 getFullyCoveredSiblings
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
5
 unwrapParsoidSections
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 getTitleFromUrl
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
6
 linearWalk
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 linearWalkBackwards
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 getRangeFirstNode
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 getRangeLastNode
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 compareRanges
88.00% covered (warning)
88.00%
22 / 25
0.00% covered (danger)
0.00%
0 / 1
23.91
 compareRangesAlmostEqualBoundaries
100.00% covered (success)
100.00%
28 / 28
100.00% covered (success)
100.00%
1 / 1
15
 isSingleCommentSignedBy
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
9
 getNewTopicsSubscriptionId
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace MediaWiki\Extension\DiscussionTools;
4
5use LogicException;
6use MediaWiki\Config\Config;
7use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentCommentItem;
8use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentThreadItem;
9use MediaWiki\MainConfigNames;
10use MediaWiki\Title\Title;
11use Wikimedia\Assert\Assert;
12use Wikimedia\Parsoid\DOM\Comment;
13use Wikimedia\Parsoid\DOM\Element;
14use Wikimedia\Parsoid\DOM\Node;
15use Wikimedia\Parsoid\DOM\Text;
16use Wikimedia\Parsoid\Utils\DOMCompat;
17use Wikimedia\Parsoid\Utils\DOMUtils;
18
19class CommentUtils {
20
21    private function __construct() {
22    }
23
24    private const BLOCK_ELEMENT_TYPES = [
25        'div', 'p',
26        // Tables
27        'table', 'tbody', 'thead', 'tfoot', 'caption', 'th', 'tr', 'td',
28        // Lists
29        'ul', 'ol', 'li', 'dl', 'dt', 'dd',
30        // HTML5 heading content
31        'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup',
32        // HTML5 sectioning content
33        'article', 'aside', 'body', 'nav', 'section', 'footer', 'header', 'figure',
34        'figcaption', 'fieldset', 'details', 'blockquote',
35        // Other
36        'hr', 'button', 'canvas', 'center', 'col', 'colgroup', 'embed',
37        'map', 'object', 'pre', 'progress', 'video'
38    ];
39
40    /**
41     * @return bool Node is a block element
42     */
43    public static function isBlockElement( Node $node ): bool {
44        return $node instanceof Element &&
45            in_array( strtolower( $node->tagName ), static::BLOCK_ELEMENT_TYPES, true );
46    }
47
48    private const SOL_TRANSPARENT_LINK_REGEX =
49        '/(?:^|\s)mw:PageProp\/(?:Category|redirect|Language)(?=$|\s)/D';
50
51    /**
52     * @return bool Node is considered a rendering-transparent node in Parsoid
53     */
54    public static function isRenderingTransparentNode( Node $node ): bool {
55        $nextSibling = $node->nextSibling;
56        return (
57            $node instanceof Comment ||
58            ( $node instanceof Element && (
59                strtolower( $node->tagName ) === 'meta' ||
60                (
61                    strtolower( $node->tagName ) === 'link' &&
62                    preg_match( static::SOL_TRANSPARENT_LINK_REGEX, $node->getAttribute( 'rel' ) ?? '' )
63                ) ||
64                // Empty inline templates, e.g. tracking templates. (T269036)
65                // But not empty nodes that are just the start of a non-empty template about-group. (T290940)
66                (
67                    strtolower( $node->tagName ) === 'span' &&
68                    in_array( 'mw:Transclusion', explode( ' ', $node->getAttribute( 'typeof' ) ?? '' ), true ) &&
69                    !static::htmlTrim( DOMCompat::getInnerHTML( $node ) ) &&
70                    (
71                        !$nextSibling || !( $nextSibling instanceof Element ) ||
72                        // Maybe we should be checking all of the about-grouped nodes to see if they're empty,
73                        // but that's prooobably not needed in practice, and it leads to a quadratic worst case.
74                        $nextSibling->getAttribute( 'about' ) !== $node->getAttribute( 'about' )
75                    )
76                )
77            ) )
78        );
79    }
80
81    /**
82     * @return bool Node was added to the page by DiscussionTools
83     */
84    public static function isOurGeneratedNode( Node $node ): bool {
85        return $node instanceof Element && (
86            DOMUtils::hasClass( $node, 'ext-discussiontools-init-replylink-buttons' ) ||
87            $node->hasAttribute( 'data-mw-comment-start' ) ||
88            $node->hasAttribute( 'data-mw-comment-end' )
89        );
90    }
91
92    /**
93     * Elements which can't have element children (but some may have text content).
94     */
95    private const NO_ELEMENT_CHILDREN_ELEMENT_TYPES = [
96        // https://html.spec.whatwg.org/multipage/syntax.html#elements-2
97        // Void elements
98        'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
99        'link', 'meta', 'param', 'source', 'track', 'wbr',
100        // Raw text elements
101        'script', 'style',
102        // Escapable raw text elements
103        'textarea', 'title',
104        // Foreign elements
105        'math', 'svg',
106        // Treated like text when scripting is enabled in the parser
107        // https://html.spec.whatwg.org/#the-noscript-element
108        'noscript',
109        // Replaced elements (that aren't already included above)
110        // https://html.spec.whatwg.org/multipage/rendering.html#replaced-elements
111        // They might allow element children, but they aren't rendered on the page.
112        'audio', 'canvas', 'iframe', 'object', 'video',
113    ];
114
115    /**
116     * @return bool If true, node can't have element children. If false, it's complicated.
117     */
118    public static function cantHaveElementChildren( Node $node ): bool {
119        return (
120            $node instanceof Comment ||
121            ( $node instanceof Element && (
122                in_array( strtolower( $node->tagName ), static::NO_ELEMENT_CHILDREN_ELEMENT_TYPES, true ) ||
123                // Thumbnail wrappers generated by MediaTransformOutput::linkWrap (T301427),
124                // for compatibility with TimedMediaHandler.
125                // There is no better way to detect them, and we can't insert markers here,
126                // because the media DOM CSS depends on specific tag names and their order :(
127                // TODO See if we can remove this condition when wgParserEnableLegacyMediaDOM=false
128                // is enabled everywhere.
129                (
130                    in_array( strtolower( $node->tagName ), [ 'a', 'span' ], true ) &&
131                    $node->firstChild &&
132                    // We always step inside a child node so this can't be infinite, silly Phan
133                    // @phan-suppress-next-line PhanInfiniteRecursion
134                    static::cantHaveElementChildren( $node->firstChild )
135                ) ||
136                // Do not insert anything inside figures when using wgParserEnableLegacyMediaDOM=false,
137                // because their CSS can't handle it (T320285).
138                strtolower( $node->tagName ) === 'figure'
139            ) )
140        );
141    }
142
143    /**
144     * Check whether the node is a comment separator (instead of a part of the comment).
145     */
146    public static function isCommentSeparator( Node $node ): bool {
147        if ( !( $node instanceof Element ) ) {
148            return false;
149        }
150
151        $tagName = strtolower( $node->tagName );
152        if ( $tagName === 'br' || $tagName === 'hr' ) {
153            return true;
154        }
155
156        // TemplateStyles followed by any of the others
157        if ( $node->nextSibling &&
158            ( $tagName === 'link' || $tagName === 'style' ) &&
159            self::isCommentSeparator( $node->nextSibling )
160        ) {
161            return true;
162        }
163
164        // Anything marked as not containing comments
165        // {{outdent}} templates
166        // {{tracked}} templates (T313097)
167        if ( DOMUtils::hasClass( $node, 'mw-notalk|outdent-template|mw-trackedTemplate' ) ) {
168            return true;
169        }
170
171        // Wikitext definition list term markup (`;`) when used as a fake heading (T265964)
172        if ( $tagName === 'dl' &&
173            count( $node->childNodes ) === 1 &&
174            $node->firstChild instanceof Element &&
175            strtolower( $node->firstChild->nodeName ) === 'dt'
176        ) {
177            return true;
178        }
179
180        return false;
181    }
182
183    /**
184     * Check whether the node is a comment content. It's a little vague what this means…
185     *
186     * @param Node $node Node, should be a leaf node (a node with no children)
187     */
188    public static function isCommentContent( Node $node ): bool {
189        return (
190            $node instanceof Text &&
191            static::htmlTrim( $node->nodeValue ?? '' ) !== ''
192        ) ||
193        (
194            static::cantHaveElementChildren( $node )
195        );
196    }
197
198    /**
199     * Get the index of $child in its parent
200     */
201    public static function childIndexOf( Node $child ): int {
202        $i = 0;
203        while ( ( $child = $child->previousSibling ) ) {
204            $i++;
205        }
206        return $i;
207    }
208
209    /**
210     * Check whether a Node contains (is an ancestor of) another Node (or is the same node)
211     */
212    public static function contains( Node $ancestor, Node $descendant ): bool {
213        // TODO can we use Node->compareDocumentPosition() here maybe?
214        $node = $descendant;
215        while ( $node && $node !== $ancestor ) {
216            $node = $node->parentNode;
217        }
218        return $node === $ancestor;
219    }
220
221    /**
222     * Find closest ancestor element using one of the given tag names.
223     *
224     * @param Node $node
225     * @param string[] $tagNames
226     */
227    public static function closestElement( Node $node, array $tagNames ): ?Element {
228        do {
229            if (
230                $node instanceof Element &&
231                in_array( strtolower( $node->tagName ), $tagNames, true )
232            ) {
233                return $node;
234            }
235            $node = $node->parentNode;
236        } while ( $node );
237        return null;
238    }
239
240    /**
241     * Find closest ancestor element that has sibling nodes
242     *
243     * @param Node $node
244     * @param string $direction Can be 'next', 'previous', or 'either'
245     */
246    public static function closestElementWithSibling( Node $node, string $direction ): ?Element {
247        do {
248            if (
249                $node instanceof Element && (
250                    ( $node->nextSibling && ( $direction === 'next' || $direction === 'either' ) ) ||
251                    ( $node->previousSibling && ( $direction === 'previous' || $direction === 'either' ) )
252                )
253            ) {
254                return $node;
255            }
256            $node = $node->parentNode;
257        } while ( $node );
258        return null;
259    }
260
261    /**
262     * Find the transclusion node which rendered the current node, if it exists.
263     *
264     * 1. Find the closest ancestor with an 'about' attribute
265     * 2. Find the main node of the about-group (first sibling with the same 'about' attribute)
266     * 3. If this is an mw:Transclusion node, return it; otherwise, go to step 1
267     *
268     * @return Element|null Transclusion node, null if not found
269     */
270    public static function getTranscludedFromElement( Node $node ): ?Element {
271        while ( $node ) {
272            // 1.
273            if (
274                $node instanceof Element &&
275                $node->getAttribute( 'about' ) &&
276                preg_match( '/^#mwt\d+$/', $node->getAttribute( 'about' ) ?? '' )
277            ) {
278                $about = $node->getAttribute( 'about' );
279
280                // 2.
281                while (
282                    ( $previousSibling = $node->previousSibling ) &&
283                    $previousSibling instanceof Element &&
284                    $previousSibling->getAttribute( 'about' ) === $about
285                ) {
286                    $node = $previousSibling;
287                }
288
289                // 3.
290                if (
291                    $node->getAttribute( 'typeof' ) &&
292                    in_array( 'mw:Transclusion', explode( ' ', $node->getAttribute( 'typeof' ) ?? '' ), true )
293                ) {
294                    break;
295                }
296            }
297
298            $node = $node->parentNode;
299        }
300        return $node;
301    }
302
303    /**
304     * Given a heading node, return the node on which the ID attribute is set.
305     *
306     * @param Element $heading Heading node (`<h1>`-`<h6>`)
307     * @return Element Headline node, normally also a `<h1>`-`<h6>` element.
308     *   In integration tests and in JS, it can be a `<span class="mw-headline">` (see T363031).
309     */
310    public static function getHeadlineNode( Element $heading ): Element {
311        // This code assumes that $wgFragmentMode is [ 'html5', 'legacy' ] or [ 'html5' ]
312        $headline = $heading;
313
314        if ( $headline->hasAttribute( 'data-mw-comment-start' ) ) {
315            // HACK: For contaminated integration tests only (see T363031)
316            $headline = $headline->parentNode;
317            Assert::precondition( $headline !== null, 'data-mw-comment-start was attached to a heading' );
318        }
319
320        if ( !$headline->getAttribute( 'id' ) && !$headline->getAttribute( 'data-mw-anchor' ) ) {
321            // HACK: For outdated integration tests only (see T363031)
322            $headline = DOMCompat::querySelector( $headline, '.mw-headline' );
323            if ( !$headline ) {
324                $headline = $heading;
325            }
326        }
327
328        return $headline;
329    }
330
331    /**
332     * Trim ASCII whitespace, as defined in the HTML spec.
333     */
334    public static function htmlTrim( string $str ): string {
335        // https://infra.spec.whatwg.org/#ascii-whitespace
336        return trim( $str, "\t\n\f\r " );
337    }
338
339    /**
340     * Get the indent level of $node, relative to $rootNode.
341     *
342     * The indent level is the number of lists inside of which it is nested.
343     */
344    public static function getIndentLevel( Node $node, Element $rootNode ): int {
345        $indent = 0;
346        while ( $node ) {
347            if ( $node === $rootNode ) {
348                break;
349            }
350            $tagName = $node instanceof Element ? strtolower( $node->tagName ) : null;
351            if ( $tagName === 'li' || $tagName === 'dd' ) {
352                $indent++;
353            }
354            $node = $node->parentNode;
355        }
356        return $indent;
357    }
358
359    /**
360     * Get an array of sibling nodes that contain parts of the given range.
361     *
362     * @return Node[]
363     */
364    public static function getCoveredSiblings( ImmutableRange $range ): array {
365        $ancestor = $range->commonAncestorContainer;
366
367        // Convert to array early because apparently NodeList acts like a linked list
368        // and accessing items by index is slow
369        $siblings = iterator_to_array( $ancestor->childNodes );
370        $start = 0;
371        $end = count( $siblings ) - 1;
372
373        // Find first of the siblings that contains the item
374        if ( $ancestor === $range->startContainer ) {
375            $start = $range->startOffset;
376        } else {
377            while ( !static::contains( $siblings[ $start ], $range->startContainer ) ) {
378                $start++;
379            }
380        }
381
382        // Find last of the siblings that contains the item
383        if ( $ancestor === $range->endContainer ) {
384            $end = $range->endOffset - 1;
385        } else {
386            while ( !static::contains( $siblings[ $end ], $range->endContainer ) ) {
387                $end--;
388            }
389        }
390
391        return array_slice( $siblings, $start, $end - $start + 1 );
392    }
393
394    /**
395     * Get the nodes (if any) that contain the given thread item, and nothing else.
396     *
397     * @param ContentThreadItem $item
398     * @param ?Node $excludedAncestorNode Node that shouldn't be included in the result, even if it
399     *     contains the item and nothing else. This is intended to avoid traversing outside of a node
400     *     which is a container for all the thread items.
401     * @return Node[]|null
402     */
403    public static function getFullyCoveredSiblings(
404        ContentThreadItem $item, ?Node $excludedAncestorNode = null
405    ): ?array {
406        $siblings = static::getCoveredSiblings( $item->getRange() );
407
408        $makeRange = static function ( $siblings ) {
409            return new ImmutableRange(
410                $siblings[0]->parentNode,
411                CommentUtils::childIndexOf( $siblings[0] ),
412                end( $siblings )->parentNode,
413                CommentUtils::childIndexOf( end( $siblings ) ) + 1
414            );
415        };
416
417        $matches = static::compareRanges( $makeRange( $siblings ), $item->getRange() ) === 'equal';
418
419        if ( $matches ) {
420            // If these are all of the children (or the only child), go up one more level
421            while (
422                ( $parent = $siblings[ 0 ]->parentNode ) &&
423                $parent !== $excludedAncestorNode &&
424                static::compareRanges( $makeRange( [ $parent ] ), $item->getRange() ) === 'equal'
425            ) {
426                $siblings = [ $parent ];
427            }
428            return $siblings;
429        }
430        return null;
431    }
432
433    /**
434     * Unwrap Parsoid sections
435     *
436     * @param Element $element Parent element, e.g. document body
437     */
438    public static function unwrapParsoidSections( Element $element ): void {
439        $sections = DOMCompat::querySelectorAll( $element, 'section[data-mw-section-id]' );
440        foreach ( $sections as $section ) {
441            $parent = $section->parentNode;
442            while ( $section->firstChild ) {
443                $parent->insertBefore( $section->firstChild, $section );
444            }
445            $parent->removeChild( $section );
446        }
447    }
448
449    /**
450     * Get a MediaWiki page title from a URL
451     *
452     * @param string $url Relative URL (from a `href` attribute)
453     * @param Config $config Config settings needed to resolve the relative URL
454     */
455    public static function getTitleFromUrl( string $url, Config $config ): ?string {
456        // Protocol-relative URLs are handled really badly by parse_url()
457        if ( str_starts_with( $url, '//' ) ) {
458            $url = "http:$url";
459        }
460
461        $bits = parse_url( $url );
462        $query = wfCgiToArray( $bits['query'] ?? '' );
463        if ( isset( $query['title'] ) ) {
464            return $query['title'];
465        }
466
467        // TODO: Set the correct base in the document?
468        $articlePath = $config->get( MainConfigNames::ArticlePath );
469        if ( str_starts_with( $url, './' ) ) {
470            // Assume this is URL in the format used by Parsoid documents
471            $url = substr( $url, 2 );
472            $path = str_replace( '$1', $url, $articlePath );
473        } elseif ( !str_contains( $url, '://' ) ) {
474            // Assume this is URL in the format used by legacy parser documents
475            $path = $url;
476        } else {
477            // External link
478            $path = $bits['path'] ?? '';
479        }
480
481        $articlePathRegexp = '/^' . str_replace(
482            '\\$1',
483            '([^?]*)',
484            preg_quote( $articlePath, '/' )
485        ) . '/';
486        $matches = null;
487        if ( preg_match( $articlePathRegexp, $path, $matches ) ) {
488            return rawurldecode( $matches[1] );
489        }
490        return null;
491    }
492
493    /**
494     * Traverse the document in depth-first order, calling the callback whenever entering and leaving
495     * a node. The walk starts before the given node and ends when callback returns a truthy value, or
496     * after reaching the end of the document.
497     *
498     * You might also think about this as processing XML token stream linearly (rather than XML
499     * nodes), as if we were parsing the document.
500     *
501     * @param Node $node Node to start at
502     * @param callable $callback Function accepting two arguments: $event ('enter' or 'leave') and
503     *     $node (Node)
504     * @return mixed Final return value of the callback
505     */
506    public static function linearWalk( Node $node, callable $callback ) {
507        $result = null;
508        [ $withinNode, $beforeNode ] = [ $node->parentNode, $node ];
509
510        while ( $beforeNode || $withinNode ) {
511            if ( $beforeNode ) {
512                $result = $callback( 'enter', $beforeNode );
513                [ $withinNode, $beforeNode ] = [ $beforeNode, $beforeNode->firstChild ];
514            } else {
515                $result = $callback( 'leave', $withinNode );
516                [ $withinNode, $beforeNode ] = [ $withinNode->parentNode, $withinNode->nextSibling ];
517            }
518
519            if ( $result ) {
520                return $result;
521            }
522        }
523        return $result;
524    }
525
526    /**
527     * Like #linearWalk, but it goes backwards.
528     *
529     * @inheritDoc ::linearWalk()
530     */
531    public static function linearWalkBackwards( Node $node, callable $callback ) {
532        $result = null;
533        [ $withinNode, $beforeNode ] = [ $node->parentNode, $node ];
534
535        while ( $beforeNode || $withinNode ) {
536            if ( $beforeNode ) {
537                $result = $callback( 'enter', $beforeNode );
538                [ $withinNode, $beforeNode ] = [ $beforeNode, $beforeNode->lastChild ];
539            } else {
540                $result = $callback( 'leave', $withinNode );
541                [ $withinNode, $beforeNode ] = [ $withinNode->parentNode, $withinNode->previousSibling ];
542            }
543
544            if ( $result ) {
545                return $result;
546            }
547        }
548        return $result;
549    }
550
551    /**
552     * @param ImmutableRange $range (must not be collapsed)
553     */
554    public static function getRangeFirstNode( ImmutableRange $range ): Node {
555        Assert::precondition( !$range->collapsed, 'Range is not collapsed' );
556        // PHP bug: childNodes can be null
557        return $range->startContainer->childNodes && $range->startContainer->childNodes->length ?
558            $range->startContainer->childNodes[ $range->startOffset ] :
559            $range->startContainer;
560    }
561
562    /**
563     * @param ImmutableRange $range (must not be collapsed)
564     */
565    public static function getRangeLastNode( ImmutableRange $range ): Node {
566        Assert::precondition( !$range->collapsed, 'Range is not collapsed' );
567        // PHP bug: childNodes can be null
568        return $range->endContainer->childNodes && $range->endContainer->childNodes->length ?
569            $range->endContainer->childNodes[ $range->endOffset - 1 ] :
570            $range->endContainer;
571    }
572
573    /**
574     * Check whether two ranges overlap, and how.
575     *
576     * Includes a hack to check for "almost equal" ranges (whose start/end boundaries only differ by
577     * "uninteresting" nodes that we ignore when detecting comments), and treat them as equal.
578     *
579     * Illustration of return values:
580     *          [    equal    ]
581     *          |[ contained ]|
582     *        [ |  contains   | ]
583     *  [overlap|start]       |
584     *          |     [overlap|end]
585     * [before] |             |
586     *          |             | [after]
587     *
588     * @return string One of:
589     *     - 'equal': Ranges A and B are equal
590     *     - 'contains': Range A contains range B
591     *     - 'contained': Range A is contained within range B
592     *     - 'after': Range A is before range B
593     *     - 'before': Range A is after range B
594     *     - 'overlapstart': Start of range A overlaps range B
595     *     - 'overlapend': End of range A overlaps range B
596     */
597    public static function compareRanges( ImmutableRange $a, ImmutableRange $b ): string {
598        // Compare the positions of: start of A to start of B, start of A to end of B, and so on.
599        // Watch out, the constant names are the opposite of what they should be.
600        $startToStart = $a->compareBoundaryPoints( ImmutableRange::START_TO_START, $b );
601        $startToEnd = $a->compareBoundaryPoints( ImmutableRange::END_TO_START, $b );
602        $endToStart = $a->compareBoundaryPoints( ImmutableRange::START_TO_END, $b );
603        $endToEnd = $a->compareBoundaryPoints( ImmutableRange::END_TO_END, $b );
604
605        // Handle almost equal ranges: When start or end boundary points of the two ranges are different,
606        // but only differ by "uninteresting" nodes, treat them as equal instead.
607        if (
608            ( $startToStart < 0 && static::compareRangesAlmostEqualBoundaries( $a, $b, 'start' ) ) ||
609            ( $startToStart > 0 && static::compareRangesAlmostEqualBoundaries( $b, $a, 'start' ) )
610        ) {
611            $startToStart = 0;
612        }
613        if (
614            ( $endToEnd < 0 && static::compareRangesAlmostEqualBoundaries( $a, $b, 'end' ) ) ||
615            ( $endToEnd > 0 && static::compareRangesAlmostEqualBoundaries( $b, $a, 'end' ) )
616        ) {
617            $endToEnd = 0;
618        }
619
620        if ( $startToStart === 0 && $endToEnd === 0 ) {
621            return 'equal';
622        }
623        if ( $startToStart <= 0 && $endToEnd >= 0 ) {
624            return 'contains';
625        }
626        if ( $startToStart >= 0 && $endToEnd <= 0 ) {
627            return 'contained';
628        }
629        if ( $startToEnd >= 0 ) {
630            return 'after';
631        }
632        if ( $endToStart <= 0 ) {
633            return 'before';
634        }
635        if ( $startToStart > 0 && $startToEnd < 0 && $endToEnd >= 0 ) {
636            return 'overlapstart';
637        }
638        if ( $endToEnd < 0 && $endToStart > 0 && $startToStart <= 0 ) {
639            return 'overlapend';
640        }
641
642        throw new LogicException( 'Unreachable' );
643    }
644
645    /**
646     * Check if the given boundary points of ranges A and B are almost equal (only differing by
647     * uninteresting nodes).
648     *
649     * Boundary of A must be before the boundary of B in the tree.
650     *
651     * @param ImmutableRange $a
652     * @param ImmutableRange $b
653     * @param string $boundary 'start' or 'end'
654     */
655    private static function compareRangesAlmostEqualBoundaries(
656        ImmutableRange $a, ImmutableRange $b, string $boundary
657    ): bool {
658        // This code is awful, but several attempts to rewrite it made it even worse.
659        // You're welcome to give it a try.
660
661        $from = $boundary === 'end' ? static::getRangeLastNode( $a ) : static::getRangeFirstNode( $a );
662        $to = $boundary === 'end' ? static::getRangeLastNode( $b ) : static::getRangeFirstNode( $b );
663
664        $skipNode = null;
665        if ( $boundary === 'end' ) {
666            $skipNode = $from;
667        }
668
669        $foundContent = false;
670        static::linearWalk(
671            $from,
672            static function ( string $event, Node $n ) use (
673                $to, $boundary, &$skipNode, &$foundContent
674            ) {
675                if ( $n === $to && $event === ( $boundary === 'end' ? 'leave' : 'enter' ) ) {
676                    return true;
677                }
678                if ( $skipNode ) {
679                    if ( $n === $skipNode && $event === 'leave' ) {
680                        $skipNode = null;
681                    }
682                    return;
683                }
684
685                if ( $event === 'enter' ) {
686                    if (
687                        CommentUtils::isCommentSeparator( $n ) ||
688                        CommentUtils::isRenderingTransparentNode( $n ) ||
689                        CommentUtils::isOurGeneratedNode( $n )
690                    ) {
691                        $skipNode = $n;
692
693                    } elseif (
694                        CommentUtils::isCommentContent( $n )
695                    ) {
696                        $foundContent = true;