Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 447
0.00% covered (danger)
0.00%
0 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
TableFixups
0.00% covered (danger)
0.00%
0 / 447
0.00% covered (danger)
0.00%
0 / 15
31152
0.00% covered (danger)
0.00%
0 / 1
 isSimpleTemplatedSpan
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
 fillDSRGap
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 hoistTransclusionInfo
0.00% covered (danger)
0.00%
0 / 62
0.00% covered (danger)
0.00%
0 / 1
210
 collectAttributishContent
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
156
 reparseTemplatedAttributes
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
90
 stripTrailingPipe
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 transferSourceBetweenCells
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
210
 mergeCells
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
 convertAttribsToContent
0.00% covered (danger)
0.00%
0 / 53
0.00% covered (danger)
0.00%
0 / 1
342
 reparseWithPreviousCell
0.00% covered (danger)
0.00%
0 / 64
0.00% covered (danger)
0.00%
0 / 1
506
 shouldAbortAttr
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 pipeStatusInContent
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
210
 putsNextSiblingInSOLState
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 getReparseType
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
272
 handleTableCellTemplates
0.00% covered (danger)
0.00%
0 / 96
0.00% covered (danger)
0.00%
0 / 1
1482
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid\Wt2Html\DOM\Handlers;
5
6use Wikimedia\Assert\Assert;
7use Wikimedia\Assert\UnreachableException;
8use Wikimedia\Parsoid\Config\Env;
9use Wikimedia\Parsoid\Core\DOMCompat;
10use Wikimedia\Parsoid\Core\Sanitizer;
11use Wikimedia\Parsoid\Core\Source;
12use Wikimedia\Parsoid\Core\SourceRange;
13use Wikimedia\Parsoid\DOM\Comment;
14use Wikimedia\Parsoid\DOM\Element;
15use Wikimedia\Parsoid\DOM\Node;
16use Wikimedia\Parsoid\DOM\Text;
17use Wikimedia\Parsoid\NodeData\DataMw;
18use Wikimedia\Parsoid\NodeData\DataParsoid;
19use Wikimedia\Parsoid\NodeData\TempData;
20use Wikimedia\Parsoid\NodeData\TemplateInfo;
21use Wikimedia\Parsoid\Utils\DiffDOMUtils;
22use Wikimedia\Parsoid\Utils\DOMDataUtils;
23use Wikimedia\Parsoid\Utils\DOMUtils;
24use Wikimedia\Parsoid\Utils\DTState;
25use Wikimedia\Parsoid\Utils\PHPUtils;
26use Wikimedia\Parsoid\Utils\PipelineUtils;
27use Wikimedia\Parsoid\Utils\Utils;
28use Wikimedia\Parsoid\Utils\WTUtils;
29use Wikimedia\Parsoid\Wt2Html\Frame;
30use Wikimedia\Parsoid\Wt2Html\PegTokenizer;
31
32/**
33 * Provides DOMTraverser visitors that fix template-induced interrupted table cell parsing
34 * by recombining table cells and/or reparsing table cell content as attributes.
35 * - handleTableCellTemplates
36 */
37class TableFixups {
38
39    private static function isSimpleTemplatedSpan( Node $node ): bool {
40        return DOMUtils::nodeName( $node ) === 'span' &&
41            // This check only works because it is called from a context
42            // where we are tracking templates.
43            $node instanceof Element && /* make phan happy */
44            DOMCompat::getAttribute( $node, 'about' ) !== null &&
45            DOMUtils::allChildrenAreTextOrComments( $node );
46    }
47
48    /**
49     * @param list<string|TemplateInfo> &$parts
50     * @param Source $source
51     * @param int $offset1
52     * @param int $offset2
53     */
54    private static function fillDSRGap( array &$parts, Source $source, int $offset1, int $offset2 ): void {
55        if ( $offset1 < $offset2 ) {
56            $parts[] = PHPUtils::safeSubstr( $source->getSrcText(), $offset1, $offset2 - $offset1 );
57        }
58    }
59
60    /**
61     * Hoist transclusion information from cell content / attributes
62     * onto the cell itself.
63     */
64    private static function hoistTransclusionInfo(
65        DTState $dtState, array $transclusions, Element $td
66    ): void {
67        // Initialize dsr for $td
68        // In `handleTableCellTemplates`, we're creating a cell w/o dsr info.
69        $tdDp = DOMDataUtils::getDataParsoid( $td );
70        if ( !Utils::isValidDSR( $tdDp->dsr ?? null ) ) {
71            $tplDp = DOMDataUtils::getDataParsoid( $transclusions[0] );
72            Assert::invariant( Utils::isValidDSR( $tplDp->dsr ?? null ), 'Expected valid DSR' );
73            $tdDp->dsr = clone $tplDp->dsr;
74        }
75
76        // Build up $parts, $pi to set up the combined transclusion info on $td.
77        // Note that content for all but the last template has been swallowed into
78        // the attributes of $td.
79        $parts = [];
80        $pi = [];
81        $lastTpl = null;
82        $prevDp = null;
83        $frame = $dtState->options['frame'];
84        $aboutIdArray = [];
85
86        $index = 0;
87        foreach ( $transclusions as $tpl ) {
88            $aboutIdArray[] = DOMCompat::getAttribute( $tpl, 'about' );
89
90            $tplDp = DOMDataUtils::getDataParsoid( $tpl );
91            Assert::invariant( Utils::isValidDSR( $tplDp->dsr ?? null ), 'Expected valid DSR' );
92
93            // Plug DSR gaps between transclusions
94            if ( !$prevDp ) {
95                self::fillDSRGap(
96                    $parts, $tdDp->dsr->source ?? $frame->getSource(),
97                    $tdDp->dsr->start, $tplDp->dsr->start );
98            } else {
99                self::fillDSRGap(
100                    $parts, $prevDp->dsr->source ?? $frame->getSource(),
101                    $prevDp->dsr->end, $tplDp->dsr->start );
102            }
103
104            // Assimilate $tpl's data-mw and data-parsoid pi info
105            $dmw = DOMDataUtils::getDataMw( $tpl );
106            foreach ( $dmw->parts ?? [] as $part ) {
107                // Template index is relative to other transclusions.
108                // This index is used to extract whitespace information from
109                // data-parsoid and that array only includes info for templates.
110                // So skip over strings here.
111                if ( !is_string( $part ) ) {
112                    // Cloning is strictly not needed here, but mimicking
113                    // code in WrapSectionsState.php
114                    $part = clone $part;
115                    $part->i = $index++;
116                }
117                $parts[] = $part;
118            }
119            PHPUtils::pushArray( $pi, $tplDp->pi ?? [ [] ] );
120            DOMDataUtils::setDataMw( $tpl, null );
121
122            $lastTpl = $tpl;
123            $prevDp = $tplDp;
124        }
125
126        $aboutId = DOMCompat::getAttribute( $lastTpl, 'about' );
127
128        // Hoist transclusion information to $td.
129        $td->setAttribute( 'typeof', 'mw:Transclusion' );
130        $td->setAttribute( 'about', $aboutId );
131
132        // Add wikitext for the table cell content following $lastTpl
133        self::fillDSRGap( $parts, $prevDp->dsr->source ?? $frame->getSource(), $prevDp->dsr->end, $tdDp->dsr->end );
134
135        // Save the new data-mw on the td
136        $dmw = new DataMw( [] );
137        $dmw->parts = $parts;
138        DOMDataUtils::setDataMw( $td, $dmw );
139        $tdDp->pi = $pi;
140
141        // td wraps everything now.
142        // Remove template encapsulation from here on.
143        // This simplifies the problem of analyzing the <td>
144        // for additional fixups (|| Boo || Baz) by potentially
145        // invoking 'reparseTemplatedAttributes' on split cells
146        // with some modifications.
147        $cell = $td;
148        while ( $cell instanceof Element && DOMCompat::getAttribute( $cell, 'about' ) === $aboutId ) {
149            $child = $cell->firstChild;
150            while ( $child ) {
151                $next = $child->nextSibling;
152                if ( $child instanceof Element &&
153                    in_array( DOMCompat::getAttribute( $child, 'about' ), $aboutIdArray, true )
154                ) {
155                    // Remove the encapsulation attributes.
156                    $child->removeAttribute( 'about' );
157                    DOMUtils::removeTypeOf( $child, 'mw:Transclusion' );
158                    // If there are no more attributes left, useless spans wrapper can be removed.
159                    if ( DOMDataUtils::getDataParsoid( $child )->getTempFlag( TempData::WRAPPER ) ) {
160                        $next = $child->firstChild ?: $child->nextSibling;
161                        DOMUtils::migrateChildren( $child, $cell, $child );
162                        $child->parentNode->removeChild( $child );
163                    }
164                }
165                $child = $next;
166            }
167            $cell = $cell->nextSibling;
168        }
169
170        // $dtState->tplInfo can be null when information is hoisted
171        // from children to $td because DOMTraverser hasn't seen the
172        // children yet!
173        if ( !$dtState->tplInfo ) {
174            $dtState->tplInfo = (object)[
175                'first' => $td,
176                'last' => $td,
177                'clear' => false
178            ];
179        }
180    }
181
182    /**
183     * Collect potential attribute content.
184     *
185     * We expect this to be text nodes without a pipe character followed by one or
186     * more nowiki spans, followed by a template encapsulation with pure-text and
187     * nowiki content. Collection stops when encountering a pipe character.
188     *
189     * @param Env $env
190     * @param Element $cell known to be <td> / <th>
191     * @param ?Element $templateWrapper
192     * @return ?array{txt: string, frags: list<?string>, transclusions: list<Element>}
193     */
194    public static function collectAttributishContent(
195        Env $env, Element $cell, ?Element $templateWrapper
196    ): ?array {
197        $buf = [];
198        $frags = [];
199        $transclusions = $templateWrapper ? [ $templateWrapper ] : [];
200
201        // Some of this logic could be replaced by DSR-based recovery of
202        // wikitext that is outside templates. But since we have to walk over
203        // templated content in this fashion anyway, we might as well use the
204        // same logic uniformly.
205
206        $traverse = static function ( ?Node $child ) use (
207            &$traverse, &$buf, &$frags, &$transclusions
208        ): bool {
209            while ( $child ) {
210                if ( $child instanceof Comment ) {
211                    // Legacy parser strips comments during parsing => drop them.
212                } elseif ( $child instanceof Text ) {
213                    $text = $child->nodeValue;
214                    $buf[] = $text;
215
216                    // Are we done accumulating?
217                    if ( preg_match( '/(?:^|[^|])\|(?:[^|]|$)/D', $text ) ) {
218                        return true;
219                    }
220                } else {
221                    '@phan-var Element $child';  /** @var Element $child */
222                    if ( DOMUtils::hasTypeOf( $child, 'mw:Transclusion' ) ) {
223                        $transclusions[] = $child;
224                    }
225
226                    if ( DOMUtils::hasTypeOf( $child, 'mw:Entity' ) ) {
227                        // Get entity's wikitext source, not rendered content.
228                        // "&#10;" is "\n" which breaks attribute parsing!
229                        $buf[] = DOMDataUtils::getDataParsoid( $child )->src ?? $child->textContent;
230                    } elseif ( DOMUtils::hasTypeOf( $child, 'mw:DOMFragment' ) ) {
231                        $fragDOM = WTUtils::getDOMFragmentContents( $child );
232                        // FIXME: This is correct only for nowikis.
233                        // For everything else, we need to figure out what needs to happen
234                        // here wrt the extension opening & closing tags.
235                        $frags[] = $fragDOM->firstChild->textContent;
236                        $buf[] = '<frag-marker>';
237                    } elseif ( self::shouldAbortAttr( $child ) ) {
238                        return true;
239                    } else {
240                        if ( $traverse( $child->firstChild ) ) {
241                            return true;
242                        }
243                    }
244                }
245
246                $child = $child->nextSibling;
247            }
248
249            return false;
250        };
251
252        if ( $traverse( $cell->firstChild ) ) {
253            return [
254                'txt' => implode( '', $buf ),
255                'frags' => $frags,
256                'transclusions' => $transclusions,
257            ];
258        } else {
259            return null;
260        }
261    }
262
263    /**
264     * T46498, second part of T52603
265     *
266     * Handle wikitext like
267     * ```
268     * {|
269     * |{{nom|Bar}}
270     * |}
271     * ```
272     * where nom expands to `style="foo" class="bar"|Bar`. The attributes are
273     * tokenized and stripped from the table contents.
274     *
275     * This method works well for the templates documented in
276     * https://en.wikipedia.org/wiki/Template:Table_cell_templates/doc
277     *
278     * Nevertheless, there are some limitations:
279     * - We assume that attributes don't contain wiki markup (apart from <nowiki>)
280     *   and end up in text or nowiki nodes.
281     * - Only a single table cell is produced / opened by the template that
282     *   contains the attributes. This limitation could be lifted with more
283     *   aggressive re-parsing if really needed in practice.
284     * - There is only a single transclusion in the table cell content. This
285     *   limitation can be lifted with more advanced data-mw construction.
286     *
287     * $cell known to be <td> / <th>
288     */
289    public static function reparseTemplatedAttributes(
290        DTState $dtState, Element $cell, ?Element $templateWrapper
291    ): void {
292        $env = $dtState->env;
293        // Collect attribute content and examine it
294        $attributishContent = self::collectAttributishContent( $env, $cell, $templateWrapper );
295        if ( !$attributishContent ) {
296            return;
297        }
298
299        /**
300         * FIXME: These checks are insufficient.
301         * Previous rounds of table fixups might have created this cell without
302         * any templated content (the while loop in handleTableCellTemplates).
303         * Till we figure out a reliable test for this, we'll reparse attributes always.
304         *
305         * // This DOM pass is trying to bridge broken parses across
306         * // template boundaries. So, if templates aren't involved,
307         * // no reason to reparse.
308         * if ( count( $attributishContent['transclusions'] ) === 0 &&
309         *     !WTUtils::fromTemplatedContent( $cell )
310         * ) {
311         *     return;
312         * }
313         */
314
315        $attrText = $attributishContent['txt'];
316        if ( !preg_match( '/(^[^|]+\|)([^|]|$)/D', $attrText, $matches ) ) {
317            return;
318        }
319        $attributishPrefix = $matches[1];
320
321        // Splice in fragment content. We added in <frag-marker> markers to prevent
322        // the above regexps from matching protected chars.
323        if ( str_contains( $attributishPrefix, '<frag-marker>' ) ) {
324            $attributishPrefix = preg_replace_callback(
325                '/<frag-marker>/',
326                static function ( $unused ) use ( &$attributishContent ) {
327                    // This is a little tricky. We want to use the content from the
328                    // fragments to reparse the string to key/val pairs but the rule,
329                    // single_cell_table_args, will invariably get tripped up on
330                    // newlines which, to this point, were shuttled through the fragment.
331                    // Core sanitizer will do this replacement in attr vals
332                    // so it's a safe normalization to do here.
333                    return preg_replace( '/\s+/', ' ', array_shift( $attributishContent['frags'] ) );
334                },
335                $attributishPrefix
336            );
337        }
338
339        // re-parse the attributish prefix
340        if ( !$dtState->tokenizer ) {
341            $dtState->tokenizer = new PegTokenizer( $env );
342        }
343        $attributeTokens = $dtState->tokenizer->tokenizeTableCellAttributes( $attributishPrefix, false );
344
345        // No attributes => nothing more to do!
346        if ( !$attributeTokens ) {
347            return;
348        }
349
350        // Note that `row_syntax_table_args` (the rule used for tokenizing above)
351        // returns an array consisting of [table_attributes, spaces, pipe]
352        $attrs = $attributeTokens[0];
353
354        // Sanitize attrs and transfer them to the td node
355        Sanitizer::applySanitizedArgs( $env->getSiteConfig(), $cell, $attrs );
356        $cellDp = DOMDataUtils::getDataParsoid( $cell );
357        // Reparsed cells start off as non-mergeable-table cells
358        // and preserve that property after reparsing
359        $cellDp->setTempFlag( TempData::MERGED_TABLE_CELL );
360        $cellDp->setTempFlag( TempData::TABLE_CELL_WITH_NO_ATTRIBUTE_SYNTAX, false );
361
362        // If the transclusion node was embedded within the td node,
363        // lift up the about group to the td node.
364        $transclusions = $attributishContent['transclusions'];
365        if ( $transclusions && ( $cell !== $transclusions[0] || count( $transclusions ) > 1 ) ) {
366            self::hoistTransclusionInfo( $dtState, $transclusions, $cell );
367        }
368
369        // Drop content that has been consumed by the reparsed attribute content.
370        // NOTE: We serialize and reparse data-object-id attributes as well which
371        // ensures stashed data-* attributes continue to be usable.
372        // FIXME: This is too naive.  What about all the care we showed in `collectAttributishContent`?
373        DOMCompat::setInnerHTML( $cell,
374            preg_replace( '/^[^|]*\|/', '', DOMCompat::getInnerHTML( $cell ) ) );
375    }
376
377    /**
378     * $cell's last character is known to be a '|' (for <td>) or '!' (for <th>)
379     */
380    private static function stripTrailingPipe( Element $cell ): ?string {
381        $lc = $cell->lastChild;
382        while ( $lc && !( $lc instanceof Text ) ) {
383            $lc = $lc->lastChild;
384        }
385
386        if ( !$lc ) {
387            // FIXME: Is this code reachable?
388            return null;
389        }
390
391        $lastChar = substr( $lc->textContent, -1 );
392        $lc->textContent = substr( $lc->textContent, 0, -1 );
393        return $lastChar;
394    }
395
396    private const PARSOID_ATTRIBUTES = [
397        'data-object-id', 'typeof', 'about', 'data-parsoid', 'data-mw'
398    ];
399
400    /**
401     * Ths is called in two cases:
402     * (a) when two cells are merged, source is transferred from source
403     *     to target cell.
404     *
405     *     This is called from mergeCells( .. )
406     *
407     * (b) when a pipe (| for td, ! for th) is being transferred from one cell
408     *     to another making the recepient cell a 'row' syntax cell. In this
409     *     case, the pipe char could come from content (when the cell has content)
410     *     OR from the attribute-terminator (when the cell has no content).
411     *     In the attribute-terminator case, the pipe transfer requires that
412     *     the openWidth dsr property be decremented by 1 for the source cell.
413     *
414     *     This is called from reparseWithPreviousCell( .. )
415     */
416    private static function transferSourceBetweenCells(
417        string $src, Element $from, Element $to, bool $emptyFromContent
418    ): void {
419        if ( DOMUtils::hasTypeOf( $to, 'mw:Transclusion' ) ) {
420            $dataMW = DOMDataUtils::getDataMw( $to );
421            array_unshift( $dataMW->parts, $src );
422        }
423
424        $rowSyntaxChar = DOMUtils::nodeName( $to ) === 'td' ? '|' : '!';
425        $fromDp = DOMDataUtils::getDataParsoid( $from );
426        if ( $rowSyntaxChar === '|' ) {
427            unset( $fromDp->startTagSrc );
428            unset( $fromDp->attrSepSrc );
429        }
430
431        $hasRowSyntax = false;
432        $toDp = DOMDataUtils::getDataParsoid( $to );
433        if ( str_ends_with( $src, $rowSyntaxChar ) ) {
434            $hasRowSyntax = true;
435            $toDp->stx = 'row';
436        }
437
438        $srcLen = strlen( $src );
439        $toDSR = $toDp->dsr ?? null;
440        if ( $toDSR ) {
441            if ( $toDSR->start ) {
442                $toDSR->start -= $srcLen;
443            }
444            if ( $hasRowSyntax && $toDSR->openWidth ) {
445                $toDSR->openWidth += 1;
446            }
447        }
448
449        $fromDSR = $fromDp->dsr ?? null;
450        if ( $fromDSR ) {
451            if ( $fromDSR->end ) {
452                $fromDSR->end -= $srcLen;
453            }
454            if ( $hasRowSyntax && $fromDSR->openWidth && $emptyFromContent ) {
455                $fromDSR->openWidth -= 1;
456            }
457        }
458    }
459
460    private static function mergeCells( string $fromSrc, Element $from, Element $to ): void {
461        // Update data-mw, DSR if $to is an encapsulation wrapper
462        self::transferSourceBetweenCells( $fromSrc, $from, $to, false );
463
464        $identicalCellTypes = DOMUtils::nodeName( $from ) === DOMUtils::nodeName( $to );
465        [ $src, $tgt ] = $identicalCellTypes ? [ $from, $to ] : [ $to, $from ];
466        // For non-identical cell types, $from is the authoritative cell but
467        // $to has transclusion attributes. So, we need to migrate data-mw,
468        // data-parsoid, etc. as well to the $tgt ($from in this case).
469        $ignoreParsoidAttributes = $identicalCellTypes;
470
471        foreach ( $src->attributes as $attr ) {
472            if ( !$ignoreParsoidAttributes || !in_array( $attr->name, self::PARSOID_ATTRIBUTES, true ) ) {
473                $tgt->setAttribute( $attr->name, $attr->value );
474            }
475        }
476
477        DOMUtils::migrateChildren( $src, $tgt, $identicalCellTypes ? $tgt->firstChild : null );
478        $src->parentNode->removeChild( $src );
479
480        // Combined cells don't merge further
481        $tgtDp = DOMDataUtils::getDataParsoid( $tgt );
482        $tgtDp->setTempFlag( TempData::MERGED_TABLE_CELL );
483        $tgtDp->setTempFlag( TempData::TABLE_CELL_WITH_NO_ATTRIBUTE_SYNTAX, false );
484    }
485
486    /**
487     * Reprocess attribute source as a WT -> HTML transform
488     * - If $cell's attributes were templated (mw:ExpandedAttrs typeof),
489     *   we would have already processed these in AttributeExpander and
490     *   stuffed it in data-mw. Just pull it out of there.
491     * - If not, extract attribute source from the $cell and process it
492     *   in a wikitext-to-fragment pipeline.
493     */
494    private static function convertAttribsToContent(
495        Env $env, Frame $frame, Element $cell, bool $leadingPipe, bool $trailingPipe
496    ): void {
497        $doc = $cell->ownerDocument;
498        $cellDp = DOMDataUtils::getDataParsoid( $cell );
499        $cellAttrSrc = $cellDp->getTemp()->attrSrc ?? null;
500
501        if ( DOMUtils::matchTypeOf( $cell, "/\bmw:ExpandedAttrs\b/" ) ) {
502            DOMUtils::removeTypeOf( $cell, 'mw:ExpandedAttrs' );
503            $dataMw = DOMDataUtils::getDataMw( $cell );
504            unset( $dataMw->attribs );
505        }
506
507        // Process attribute wikitext as HTML
508        $leadingPipeChar = DOMUtils::nodeName( $cell ) === 'td' ? '|' : '!';
509        $fromTpl = WTUtils::fromTemplatedContent( $cell );
510        if ( !preg_match( "#['[{<]#", $cellAttrSrc ) ) {
511            // Optimization:
512            // - SOL constructs like =-*# won't be found here
513            // - If no non-sol wikitext constructs, this will just a plain string
514            $str = ( $leadingPipe ? $leadingPipeChar : '' ) .
515                $cellAttrSrc .
516                ( $cellAttrSrc && $trailingPipe ? '|' : '' );
517            $children = [ $doc->createTextNode( $str ) ];
518        } else {
519            if ( isset( $cellDp->startTagSrc ) ) {
520                $attrSrcOffset = strlen( $cellDp->startTagSrc );
521            } elseif ( ( $cellDp->stx ?? '' ) === 'row' ) {
522                $attrSrcOffset = 2;
523            } else {
524                $attrSrcOffset = 1;
525            }
526            $frag = PipelineUtils::processContentInPipeline(
527                $env, $frame, $cellAttrSrc, [
528                    'sol' => false,
529                    'toplevel' => !$fromTpl,
530                    'srcOffsets' => $fromTpl ? null : new SourceRange(
531                        $cellDp->tsr->start + $attrSrcOffset, $cellDp->tsr->end - 1
532                    ),
533                    'pipelineType' => 'wikitext-to-fragment',
534                    'pipelineOpts' => [ 'inTemplate' => $fromTpl, 'inlineContext' => true ]
535                ]
536            );
537
538            if ( $leadingPipe ) {
539                $fc = $frag->firstChild;
540                if ( $fc instanceof Text ) {
541                    $fc->textContent = $leadingPipeChar . $fc->textContent;
542                } else {
543                    $frag->insertBefore( $doc->createTextNode( $leadingPipeChar ), $fc );
544                }
545            }
546            if ( $trailingPipe ) {
547                $lc = $frag->lastChild;
548                if ( $lc instanceof Text ) {
549                    $lc->textContent .= '|';
550                } else {
551                    $frag->appendChild( $doc->createTextNode( '|' ) );
552                }
553            }
554            $children = DOMUtils::childNodes( $frag );
555        }
556
557        // Append new children
558        $sentinel = $cell->firstChild;
559        foreach ( $children as $c ) {
560            $cell->insertBefore( $c, $sentinel );
561        }
562
563        // Remove $cell's attributes
564        foreach ( iterator_to_array( $cell->attributes ) as $attr ) {
565            if ( !in_array( $attr->name, self::PARSOID_ATTRIBUTES, true ) ) {
566                $cell->removeAttribute( $attr->name );
567            }
568        }
569
570        // Remove shadow attributes to suppress them from wt2wt output!
571        unset( $cellDp->a );
572        unset( $cellDp->sa );
573
574        // Update DSR
575        if ( !$fromTpl ) {
576            $excessDP = strlen( $cellAttrSrc ) + (int)$leadingPipe + (int)$trailingPipe;
577            $cellDp->dsr->openWidth -= $excessDP;
578        }
579
580        // This has no attributes now
581        $cellDp->setTempFlag( TempData::TABLE_CELL_WITH_NO_ATTRIBUTE_SYNTAX );
582    }
583
584    /**
585     * Given: $cell is not a NON_MERGEABLE_TABLE_CELL
586     * => $cell syntax is of the form: "|..." or "|..|.." (if <td>)
587     *                             or: "!..." or "!..|.." (if <th>)
588     *
589     * Examine combined $prev and $cell syntax to see how it should
590     * have actually parsed and fix up $prev & $cell appropriately.
591     *
592     * Reparse always succeeds except in one case.
593     *
594     * When cells are merged, this returns the merged cell's next sibling.
595     * This effectively skips further TableFixups processing on the merged cell
596     * and its children. This is acceptable because the only way for this cell
597     * to have td/th cells in it is via nested tables. In that case, we wouldn't
598     * have table-fixup situations because Parsoid doesn't support nested templates.
599     *
600     * @param DTState $dtState
601     * @param Element $cell
602     * @return ?Node|bool
603     */
604    private static function reparseWithPreviousCell( DTState $dtState, Element $cell ) {
605        // NOTE: The comments in this method always assume
606        // <td> && '|', but sometimes <th> & '!' are involved.
607
608        $env = $dtState->env;
609        $frame = $dtState->options['frame'];
610
611        $prev = $cell->previousSibling;
612        '@phan-var Element $prev'; // @var Element $prev
613
614        $prevIsTd = DOMUtils::nodeName( $prev ) === 'td';
615        $prevDp = DOMDataUtils::getDataParsoid( $prev );
616        $prevHasAttrs = !$prevDp->getTempFlag( TempData::TABLE_CELL_WITH_NO_ATTRIBUTE_SYNTAX );
617
618        $cellIsTd = DOMUtils::nodeName( $cell ) === 'td';
619        $cellDp = DOMDataUtils::getDataParsoid( $cell );
620        $cellHasAttrs = !$cellDp->getTempFlag( TempData::TABLE_CELL_WITH_NO_ATTRIBUTE_SYNTAX );
621
622        // Even though we have valid dsr for $prev as a condition of entering
623        // here, use tsr start because dsr computation may have expanded the range
624        // to include fostered content
625        $prevDsr = clone $prevDp->dsr;
626        $prevDsr->start = $prevDp->tsr->start;
627
628        $prevCellSrc = $prevDsr->substr( $frame->getSource() );
629
630        // $prevCellContent = substr( $prevCellSrc, $prevDp->dsr->openWidth );
631        // The following is equivalent because td/th has zero end-tag width
632        $prevCellContent = $prevDsr->innerSubstr( $frame->getSource() );
633
634        // Parsoid currently doesn't support parsing "|<--cmt-->|" as
635        // a "||" which legacy parser does. We won't support this.
636        //
637        // FIXME: $prev content could have a {{..}} that ended in a "|"
638        // and that check is missing here. For now, we won't support this
639        // use case unless necessary.
640        $prevHasTrailingPipe =
641            ( $cellIsTd && str_ends_with( $prevCellContent, "|" ) ) ||
642            ( !$cellIsTd && !$prevIsTd && str_ends_with( $prevCellContent, "!" ) );
643
644        $next = $cell->nextSibling;
645        if ( $prevHasTrailingPipe ) {
646            // $prev is of form "..|"
647            // => no cell merging
648            //    strip "|" from $prev
649            //    migrate "|" to $cell
650            $strippedChar = self::stripTrailingPipe( $prev );
651            if ( !$strippedChar ) {
652                // We saw these in T384737, it's worth keeping around these conservative
653                // checks for the time being
654                $env->log( "error/wt2html", "TableFixups: stripTrailingPipe failed." );
655                return false;
656            } else {
657                self::transferSourceBetweenCells(
658                    // $prevHasTrailingPipe => $prevCellContent !== '' => last arg is false
659                    $strippedChar, $prev, $cell, false /* emptyFromContent */
660                );
661                return true;
662            }
663        } elseif ( $prevIsTd &&
664            $prevDp->getTempFlag( TempData::NON_MERGEABLE_TABLE_CELL )
665            && ( $prevDp->stx ?? '' ) !== 'row'
666        ) {
667            if ( $prevCellContent !== '' ) {
668                // $prev is of form "||.." in SOL position, no attributes, some content
669                // Combined wikitext is "||..|.."
670                // => <td>..|..</td>
671                self::convertAttribsToContent( $env, $frame, $cell, true, true );
672                self::mergeCells( $prevCellSrc, $prev, $cell );
673                return $next;
674            } else {
675                // $prev is of form "||" in SOL position, no attributes, no content
676                // Combined wikitext is "|||.."
677                // => <td></td><td..>..</td>
678                //    migrate "|" to $cell
679                self::transferSourceBetweenCells( '|', $prev, $cell, true /* emptyFromContent */ ); // '!'
680                return true;
681            }
682        } elseif ( !$prevHasAttrs ) {
683            // $prev has no attributes and is of form "|.." in SOL posn OR "||.." in non-SOL posn
684            // => merge $prev into $cell
685            //    if $cell had attributes, those become $cell's leading content with a trailing pipe
686            if ( $cellIsTd && $cellHasAttrs ) {
687                self::convertAttribsToContent( $env, $frame, $cell, false, true );
688            }
689
690            // If $cell is a <th>, we need a pipe for us to reprocess $prev's content
691            // as $cell's attributes. So, <th> without attributes need special handling.
692            if ( !$cellIsTd && !$cellHasAttrs ) {
693                // $cell's "!" char should become content now when $prev
694                // and $cell are merged below. This code is equivalent to
695                // calling convertAttribsToContent( $env, $frame, $cell, true, false )
696                $pipe = $cell->ownerDocument->createTextNode( '!' );
697                $cell->insertBefore( $pipe, $cell->firstChild );
698            } elseif ( $prevCellContent !== '' ) {
699                // If $prev cell had content, those become $cell's attributes
700                $reparseSrc = $prevCellContent . '|';
701
702                // Reparse the attributish prefix
703                if ( !$dtState->tokenizer ) {
704                    $dtState->tokenizer = new PegTokenizer( $env );
705                }
706                $attributeTokens = $dtState->tokenizer->tokenizeTableCellAttributes( $reparseSrc, false );
707                if ( is_array( $attributeTokens ) ) {
708                    // Note that `row_syntax_table_args` (the rule used for tokenizing above)
709                    // returns an array consisting of [table_attributes, spaces, pipe]
710                    $attrs = $attributeTokens[0];
711                    Sanitizer::applySanitizedArgs( $env->getSiteConfig(), $cell, $attrs );
712
713                    // Remove all $prev's children
714                    DOMCompat::replaceChildren( $prev );
715                } else {
716                    // FIXME: Why would this happen?
717                    //        For now, should we just log errors to better understand this?
718                    //
719                    // Failed to successfully reparse $reparseSrc as table cell attributes
720                    // We'll let the cells merge, but we have to convert cell's attributes to content as well
721                    if ( $cellIsTd ) {
722                        // The leading pipe should become content since we skipped it
723                        // in the call to convertAttribsToContent above.
724                        $pipe = $cell->ownerDocument->createTextNode( '|' );
725                        $cell->insertBefore( $pipe, $cell->firstChild );
726                    } elseif ( $cellHasAttrs ) {
727                        // We skipped <th> above
728                        self::convertAttribsToContent( $env, $frame, $cell, true, true );
729                    }
730                }
731            }
732
733            // Merge cells
734            self::mergeCells( $prevCellSrc, $prev, $cell );
735            return $next;
736        } elseif ( $prevCellContent === '' ) {
737            // $prev has attributes and is of form "|..|" in SOL or "||..|" in non-SOL
738            // => no cell merging,
739            //    $prev's attributes are actually its contents
740            //    migrate "|" to $cell
741            self::convertAttribsToContent( $env, $frame, $prev, false, false );
742            self::transferSourceBetweenCells( '|', $prev, $cell, true /* emptyFromContent */ );
743            return true;
744        } else {
745            // $prev has attributes and is of form "|..|.." in SOL or "||..|.." in non-SOL
746            // => $cell merges into $prev (its attrs & pipes become content)
747            self::convertAttribsToContent( $env, $frame, $cell, true, true );
748            self::mergeCells( $prevCellSrc, $prev, $cell );
749            return $next;
750        }
751
752        // Should not get here. The throw ensures that code refactors that forget
753        // to handle the missing scenario will log errors vs. silently failing.
754        // @phan-suppress-next-line PhanPluginUnreachableCode
755        throw new UnreachableException( 'TableFixups:reparseWithPreviousCell: Unexpected scenario!' );
756    }
757
758    /**
759     * The legacy parser naively aborts attributes on '/\[\[|-\{/'
760     * Wikilinks and language converter constructs should follow suit
761     */
762    private static function shouldAbortAttr( Element $child ): bool {
763        return DOMUtils::matchRel( $child, WTUtils::WIKILINK_SYNTAX_CONSTRUCTS_REGEXP ) ||
764            WTUtils::isGeneratedFigure( $child );
765    }
766
767    private static function pipeStatusInContent(
768        Element $node, string $testRE, bool $inTplContent, bool $noAttrReparsing = false
769    ): ReparseScenario {
770        $about = null;
771        $child = $node->firstChild;
772        while ( $child ) {
773            if ( $inTplContent &&
774                $child instanceof Text &&
775                preg_match( $testRE, $child->textContent )
776            ) {
777                return $noAttrReparsing ? ReparseScenario::MAYBE_SPLIT_CELL : ReparseScenario::MAYBE_REPARSE_ATTRS;
778            }
779
780            if ( $child instanceof Element ) {
781                if ( $about && DOMCompat::getAttribute( $child, 'about' ) !== $about ) {
782                    $inTplContent = false;
783                    $about = null;
784                }
785
786                if ( !$inTplContent && DOMUtils::hasTypeOf( $child, 'mw:Transclusion' ) ) {
787                    $inTplContent = true;
788                    $about = DOMCompat::getAttribute( $child, 'about' );
789                }
790
791                // FIXME: Extlinks can hide pipes in dom fragments, but we are not handling that
792                // right now -- it is likely an edge case and it is icky to deal with it.
793                // There can be other sources of dom fragments (parser functions returning HTML,)
794                // that could hide pipes but it is unclear we need to support that form of
795                // string gluing here. For now, we treat that as unsupported behavior unless
796                // we find real uses that need to be dealt with.
797                if ( !DOMUtils::hasTypeOf( $child, 'mw:DOMFragment' ) ) {
798                    // "|" chars in extension/language variant content don't trigger
799                    // table-cell parsing since they have higher precedence in tokenization
800                    if ( self::shouldAbortAttr( $child ) ) {
801                        $noAttrReparsing = true;
802                    }
803
804                    // A "|" char in the HTML will trigger table cell tokenization.
805                    // Ex: "| foobar <div> x | y </div>" will split the <div>
806                    // in table-cell tokenization context.
807                    $status = self::pipeStatusInContent(
808                        $child, $testRE, $inTplContent, $noAttrReparsing );
809                    if ( $status !== ReparseScenario::NOT_NEEDED ) {
810                        return $status;
811                    }
812
813                    // Continue with next sibling to keep looking for reparse opportunities
814                }
815            }
816
817            $child = $child->nextSibling;
818        }
819
820        return ReparseScenario::NOT_NEEDED;
821    }
822
823    /**
824     * Does this table cell put next sibling in a SOL state?
825     * If the cell's content effectively ends in a newline, it creates
826     * SOL context in the source markup for the following table cell
827     */
828    private static function putsNextSiblingInSOLState( Element $cell ): bool {
829        return (bool)preg_match(
830            "/\n(?:" . Utils::COMMENT_REGEXP_FRAGMENT . ")*\s*$/",
831            DOMCompat::getInnerHTML( $cell )
832        );
833    }
834
835    /**
836     * $cell is known to be <td>/<th>, and known to be a wikitext tag, not HTML tag.
837     * $prev is $cell's previous sibling.
838     *
839     * Here are the requirements:
840     * 1. $prev should not be a HTML cell
841     * 2. $prev should have valid DSR
842     * 3. $cell should come from a template
843     *    Template wrapping, which happens prior to this pass, may have combined
844     *    various regions. The important indicator of whether we want to try
845     *    to combine is if the $cell was the first node of a template.
846     * 4. $cell should not be an already merged cell (we can revisit this if necessary)
847     *    OR we should not have attempted and failed a merge.
848     * 5. $cell should not be marked unmergeable (td-td, th-th, th-td scenarios)
849     *    OR we are in a td-th scenario (even if $prev, a $td, is marked unmergable)
850     * 6. $prev & $cell shouldn't be on different syntactic lines
851     */
852    private static function getReparseType( Element $cell, DTState $dtState ): ReparseScenario {
853        $cellIsTd = DOMUtils::nodeName( $cell ) === 'td';
854        $dp = DOMDataUtils::getDataParsoid( $cell );
855        $prev = $cell->previousSibling;
856        $prevDp = $prev instanceof Element ? DOMDataUtils::getDataParsoid( $prev ) : null;
857        if (
858            $prevDp !== null &&
859            // Condition 3
860            $dp->getTempFlag( TempData::AT_SRC_START ) &&
861            // Condition 4
862            !$dp->getTempFlag( TempData::MERGED_TABLE_CELL ) &&
863            !$dp->getTempFlag( TempData::FAILED_REPARSE ) &&
864            // Conditions 1 & 2 (moved below the above cheaper checks)
865            !WTUtils::hasLiteralHTMLMarker( $prevDp ) &&
866            Utils::isValidDSR( $prevDp->dsr ?? null, true ) &&
867            // Condition 5
868            (
869                !$dp->getTempFlag( TempData::NON_MERGEABLE_TABLE_CELL ) ||
870                ( DOMUtils::nodeName( $prev ) === 'td' && !$cellIsTd /* th */ )
871            ) &&
872            // Condition 6
873            !self::putsNextSiblingInSOLState( $prev )
874        ) {
875            return ReparseScenario::MAYBE_COMBINE_WITH_PREV_CELL;
876        }
877
878        // FIXME: We're traversing with the outermost encapsulation, but encapsulations
879        // can be nested (ie. template in extension content) so the check is insufficient.
880        $inTplContent = $dtState->tplInfo !== null &&
881            DOMUtils::hasTypeOf( $dtState->tplInfo->first, 'mw:Transclusion' );
882
883        $testRE = $cellIsTd ? '/[|]/' : '/[!|]/';
884        $noAttrReparsing = !$dp->getTempFlag( TempData::TABLE_CELL_WITH_NO_ATTRIBUTE_SYNTAX ) ||
885            // In TokenizerUtils::buildTableTokens(), we have a special case to add the
886            // no attribute syntax flag to || found in SOL position, since, coming from a
887            // template, we don't have the context of whether the cell is truly at SOL
888            // or if this should be interpreted as row syntax
889            ( $dp->getTempFlag( TempData::NON_MERGEABLE_TABLE_CELL ) &&
890                // Alternatively, we can check for SOL
891                // ( $cell->previousSibling instanceof Text &&
892                //     preg_match( '/\n/', $cell->previousSibling->nodeValue ?? '' ) ) );
893                ( $dp->stx ?? '' ) !== 'row' );
894        return self::pipeStatusInContent( $cell, $testRE, $inTplContent, $noAttrReparsing );
895    }
896
897    /**
898     * In a wikitext-syntax-table-parsing context, the meaning of
899     * "|", "||", "!", "!!" is context-sensitive.  Additionally, the
900     * complete syntactical construct for a table cell (including leading
901     * pipes, attributes, and content-separating pipe char) might straddle
902     * a template boundary - with some content coming from the top-level and
903     * some from a template.
904     *
905     * This impacts parsing of tables when some cells are templated since
906     * Parsoid parses template content independent of top-level content
907     * (without any preceding context). This means that Parsoid's table-cell
908     * parsing in templated contexts might be incorrect.
909     *
910     * To deal with this, Parsoid implements this table-fixups pass that
911     * has to deal with cell-merging and cell-reparsing scenarios.
912     *
913     * HTML-syntax cells and non-templated cells without any templated content
914     * are not subject to this transformation and can be skipped right away.
915     *
916     * FIXME: This pass can benefit from a customized procsssor rather than
917     * piggyback on top of DOMTraverser since the DOM can be significantly
918     * mutated in these handlers.
919     *
920     * @param Element $tableOrCell If a cell, $cell is known to be <td>/<th>
921     * @param DTState $dtState
922     * @return mixed
923     */
924    public static function handleTableCellTemplates( Element $tableOrCell, DTState $dtState ) {
925        $cellName = $nodeName = DOMUtils::nodeName( $tableOrCell );
926        $isTemplatedCell = $isTemplatedNode = DOMUtils::hasTypeOf( $tableOrCell, 'mw:Transclusion' );
927        if ( $nodeName === 'table' ) {
928            // If the table is templated and is from a well-balanced template, individual cells
929            // had been expanded in the preprocessor and there is no need to examine individual
930            // cells for reparsing. Skip the entire table.
931            if ( $isTemplatedNode && DOMDataUtils::getDataMw( $tableOrCell )->fromWellBalancedTemplate() ) {
932                return $tableOrCell->nextSibling;
933            }
934            return true;
935        }
936
937        $cell = $tableOrCell;
938        if ( WTUtils::isLiteralHTMLNode( $cell ) ) {
939            return true;
940        }
941
942        $cellDp = DOMDataUtils::getDataParsoid( $cell );
943        if ( isset( $cellDp->getTemp()->cellAttrTerminatorSeen ) ) {
944            self::convertAttribsToContent( $dtState->env, $dtState->options['frame'], $cell, false, true );
945            unset( $cellDp->getTemp()->cellAttrTerminatorSeen );
946            // Reprocess $cell in case this round makes it suitable
947            // for additional processing.
948            return $cell;
949        }
950        $reparseType = self::getReparseType( $cell, $dtState );
951
952        // Deal with <th> special case where "!! foo" is parsed as <th>! foo</th>
953        // but should have been parsed as <th>foo</th>.
954        if ( $cellName === 'th' && $isTemplatedCell &&
955            // Nothing to do here if it is going to be merged with previous cell
956            $reparseType !== ReparseScenario::MAYBE_COMBINE_WITH_PREV_CELL &&
957            // The ! wouldn't be the first content char if attrs were present
958            $cellDp->getTempFlag( TempData::TABLE_CELL_WITH_NO_ATTRIBUTE_SYNTAX ) &&
959            // Previous cell shouldn't put $cell in SOL context
960            (
961                $cell->previousSibling instanceof Element &&
962                !self::putsNextSiblingInSOLState( $cell->previousSibling )
963            )
964        ) {
965            $fc = DiffDOMUtils::firstNonSepChild( $cell );
966            if ( $fc instanceof Text ) {
967                $leadingText = $fc->nodeValue;
968                if ( str_starts_with( $leadingText, "!" ) ) {
969                    $fc->nodeValue = substr( $leadingText, 1 );
970                    $cellDp->stx = 'row';
971                    $cellDp->setTempFlag( TempData::NON_MERGEABLE_TABLE_CELL );
972                }
973            }
974        }
975
976        if ( $reparseType === ReparseScenario::NOT_NEEDED ) {
977            return true;
978        }
979
980        if ( $reparseType === ReparseScenario::MAYBE_COMBINE_WITH_PREV_CELL ) {
981            $res = self::reparseWithPreviousCell( $dtState, $cell );
982            if ( $res !== false ) { // common case
983                return $res;
984            } else {
985                // Clear property and retry $cell for other reparses
986                // The DOMTraverser will resume the handler on the
987                // returned $cell.
988                $cellDp->setTempFlag( TempData::FAILED_REPARSE );
989                return $cell;
990            }
991        }
992
993        // If the cell didn't have attrs, extract and reparse templated attrs
994        if (
995            $reparseType === ReparseScenario::MAYBE_REPARSE_ATTRS &&
996            $cellDp->getTempFlag( TempData::TABLE_CELL_WITH_NO_ATTRIBUTE_SYNTAX )
997        ) {
998            $templateWrapper = $isTemplatedCell ? $cell : null;
999            self::reparseTemplatedAttributes( $dtState, $cell, $templateWrapper );
1000        }
1001
1002        // Now, examine the <td> to see if it hides additional <td>s
1003        // and split it up if required.
1004        //
1005        // DOMTraverser will process the new cell and invoke
1006        // handleTableCellTemplates on it which ensures that
1007        // if any additional attribute fixup or splits are required,
1008        // they will get done.
1009        $origCell = $cell;
1010        $newCell = null;
1011        $newCellInsertPosn = $cell->nextSibling;
1012        $ownerDoc = $cell->ownerDocument;
1013        $tplStart = null;
1014        $tplAbout = null;
1015        $transclusions = [];
1016        $needsTplInfoHoisted = false;
1017        $isTd = $cellName === 'td';
1018        $child = $cell->firstChild;
1019        while ( $child ) {
1020            $next = $child->nextSibling;
1021
1022            if ( $newCell ) {
1023                $newCell->appendChild( $child );
1024                $cell = $newCell;
1025            }
1026
1027            if ( DOMUtils::hasTypeOf( $child, 'mw:Transclusion' ) ) {
1028                '@phan-var Element $child'; // @var Element $child
1029                $tplStart = $child;
1030                $transclusions[] = $child;
1031                $tplAbout = DOMCompat::getAttribute( $child, 'about' );
1032            } elseif ( !$child instanceof Element || DOMCompat::getAttribute( $child, 'about' ) !== $tplAbout ) {
1033                $tplStart = null;
1034                $tplAbout = null;
1035            }
1036
1037            if ( $child instanceof Text || ( $tplStart !== null && self::isSimpleTemplatedSpan( $child ) ) ) {
1038                // FIXME: This skips over scenarios like <div>foo||bar</div>.
1039                $hasSpanWrapper = !( $child instanceof Text );
1040                $match1 = $match2 = null;
1041
1042                // Find the first match of ||
1043                preg_match( '/^((?:[^|]*(?:\|[^|])?)*)\|\|(.*)$/D', $child->textContent, $match1 );
1044                if ( $isTd ) {
1045                    $match = $match1;
1046                } else {
1047                    // Find the first match !!
1048                    preg_match( '/^((?:[^!]*(?:\![^!])?)*)\!\!(.*)$/D', $child->textContent, $match2 );
1049
1050                    // Pick the shortest match
1051                    if ( $match1 && $match2 ) {
1052                        $match = strlen( $match1[1] ?? '' ) < strlen( $match2[1] ?? '' )
1053                            ? $match1
1054                            : $match2;
1055                    } else {
1056                        $match = $match1 ?: $match2;
1057                    }
1058                }
1059
1060                if ( $match ) {
1061                    // Adjust $child's content & create $newCell
1062                    $child->textContent = $match[1] ?? '';
1063
1064                    $newCell = $ownerDoc->createElement( DOMUtils::nodeName( $cell ) );
1065                    $newCell->appendChild( $ownerDoc->createTextNode( $match[2] ?? '' ) );
1066
1067                    $newCellDp = new DataParsoid;
1068                    // This new cell has 'row' stx (would be set if the tokenizer had parsed it)
1069                    $newCellDp->stx = 'row';
1070                    $newCellDp->setTempFlag( TempData::TABLE_CELL_WITH_NO_ATTRIBUTE_SYNTAX );
1071                    // It is important to set this so that when $newCell is processed by this pass,
1072                    // it won't accidentally recombine again with the previous cell!
1073                    $newCellDp->setTempFlag( TempData::NON_MERGEABLE_TABLE_CELL );
1074                    DOMDataUtils::setDataParsoid( $newCell, $newCellDp );
1075
1076                    $origCell->parentNode->insertBefore( $newCell, $newCellInsertPosn );
1077
1078                    if ( $hasSpanWrapper ) {
1079                        // $hasSpanWrapper above ensures $child is a span.
1080                        '@phan-var Element $child'; // @var Element $child
1081                        $about = DOMCompat::getAttribute( $child, 'about' );
1082                        $needsTplInfoHoisted = true;
1083                    } else {
1084                        // Refetch the about attribute since 'reparseTemplatedAttributes'
1085                        // might have added one to it.
1086                        $about = DOMCompat::getAttribute( $origCell, 'about' );
1087                    }
1088
1089                    // about may not be present if the cell was inside
1090                    // wrapped template content rather than being part
1091                    // of the outermost wrapper.
1092                    if ( $about !== null ) {
1093                        $newCell->setAttribute( 'about', $about );
1094                        // This update is necessary to prevent DOMTraverser
1095                        // from clearing dtState->tplInfo prematurely.
1096                        if ( $dtState->tplInfo?->last === $cell ) {
1097                            $dtState->tplInfo->last = $newCell;
1098                        }
1099                    }
1100                }
1101            }
1102
1103            $child = $next;
1104        }
1105
1106        // Fix up transclusion wrapping (but only if we created new cells)
1107        if ( $needsTplInfoHoisted ) {
1108            self::hoistTransclusionInfo( $dtState, $transclusions, $origCell );
1109            $dtState->tplInfo->last = $newCell;
1110        }
1111
1112        return true;
1113    }
1114}