Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 201
0.00% covered (danger)
0.00%
0 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
QuoteTransformer
0.00% covered (danger)
0.00%
0 / 201
0.00% covered (danger)
0.00%
0 / 13
6806
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 reset
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 startNewChunk
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 onTag
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
30
 onNewline
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 onEnd
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 onCompoundTk
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 onAny
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 onQuote
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 processQuotes
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
462
 convertBold
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 convertQuotesToTags
0.00% covered (danger)
0.00%
0 / 77
0.00% covered (danger)
0.00%
0 / 1
650
 quoteToTag
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
182
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid\Wt2Html\TT;
5
6use Wikimedia\Assert\Assert;
7use Wikimedia\Assert\UnreachableException;
8use Wikimedia\Parsoid\Core\SourceRange;
9use Wikimedia\Parsoid\NodeData\DataParsoid;
10use Wikimedia\Parsoid\Tokens\CompoundTk;
11use Wikimedia\Parsoid\Tokens\EmptyLineTk;
12use Wikimedia\Parsoid\Tokens\EndTagTk;
13use Wikimedia\Parsoid\Tokens\EOFTk;
14use Wikimedia\Parsoid\Tokens\NlTk;
15use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
16use Wikimedia\Parsoid\Tokens\TagTk;
17use Wikimedia\Parsoid\Tokens\Token;
18use Wikimedia\Parsoid\Tokens\XMLTagTk;
19use Wikimedia\Parsoid\Utils\PHPUtils;
20use Wikimedia\Parsoid\Utils\TokenUtils;
21use Wikimedia\Parsoid\Wt2html\TokenHandlerPipeline;
22use Wikimedia\Parsoid\Wt2html\TokenizerUtils;
23
24/**
25 * MediaWiki-compatible italic/bold handling as a token stream transformation.
26 */
27class QuoteTransformer extends LineBasedHandler {
28    /** Chunks alternate between quote tokens and sequences of non-quote
29     * tokens.  The quote tokens are later replaced with the actual tag
30     * token for italic or bold.  The first chunk is a non-quote chunk.
31     */
32    private array $chunks;
33
34    /**
35     * The current chunk we're accumulating into.
36     */
37    private array $currentChunk;
38
39    /**
40     * Last italic / last bold open tag seen.  Used to add autoInserted flags
41     * where necessary.
42     */
43    private array $last;
44
45    /**
46     * @param TokenHandlerPipeline $manager manager environment
47     * @param array $options options
48     */
49    public function __construct( TokenHandlerPipeline $manager, array $options ) {
50        parent::__construct( $manager, $options );
51        $this->reset();
52    }
53
54    /**
55     * Reset the buffering of chunks
56     */
57    private function reset(): void {
58        // Chunks alternate between quote tokens and sequences of non-quote
59        // tokens.  The quote tokens are later replaced with the actual tag
60        // token for italic or bold.  The first chunk is a non-quote chunk.
61        $this->chunks = [];
62        // The current chunk we're accumulating into.
63        $this->currentChunk = [];
64        // last italic / last bold open tag seen.  Used to add autoInserted flags
65        // where necessary.
66        $this->last = [];
67
68        $this->onAnyEnabled = false;
69    }
70
71    /**
72     * Make a copy of the token context
73     */
74    private function startNewChunk(): void {
75        $this->chunks[] = $this->currentChunk;
76        $this->currentChunk = [];
77    }
78
79    /**
80     * Handles mw-quote tokens and td/th tokens
81     * @inheritDoc
82     */
83    public function onTag( XMLTagTk $token ): ?array {
84        $tkName = $token->getName();
85        if ( $tkName === 'mw-quote' ) {
86            return $this->onQuote( $token );
87        } elseif (
88            ( $tkName === 'td' || $tkName === 'th' ) &&
89            !TokenUtils::isHTMLTag( $token )
90        ) {
91            return $this->processQuotes( $token );
92        } else {
93            return null;
94        }
95    }
96
97    /**
98     * On encountering a NlTk, processes quotes on the current line
99     * @inheritDoc
100     */
101    public function onNewline( NlTk $token ): ?array {
102        return $this->processQuotes( $token );
103    }
104
105    /**
106     * On encountering an EOFTk, processes quotes on the current line
107     * @inheritDoc
108     */
109    public function onEnd( EOFTk $token ): ?array {
110        return $this->processQuotes( $token );
111    }
112
113    /**
114     * Process nested tokens and update the compound token
115     * for where the integrity of the token isn't compromised.
116     *
117     * @inheritDoc
118     */
119    public function onCompoundTk( CompoundTk $ctk, TokenHandler $tokensHandler ): ?array {
120        if ( $ctk instanceof EmptyLineTk ) {
121            // TSP might create EmptyLineTk by swallowing a NlTk into it
122            // rather than requiring it to precede a EmptyLineTk.
123            // So, call processQuotes always.
124            // * If there was a NlTk seen before it, the buffers are empty,
125            //   and we return null and $ctk is passed through.
126            // * If there was no NlTk before it (TSP case), we effectively
127            //   flush the buffers and send the $ctk after that.
128            // In either case, we are good.
129            return $this->processQuotes( $ctk );
130        }
131
132        $newToks = $tokensHandler->process( $ctk->getNestedTokens() );
133        if ( $ctk->setsEOLContext() ) {
134            $flushedOutput = $this->processQuotes();
135            if ( $flushedOutput ) {
136                PHPUtils::pushArray( $newToks, $flushedOutput );
137            }
138            $ctk->setNestedTokens( $newToks );
139            return null;
140        } else {
141            throw new UnreachableException(
142                "QuoteTransformer: We don't support non-eol-setting compound tokens."
143            );
144
145            // An alternative if/when we support other compound tokens
146            // that end up in this else branch would be to flatten them out.
147            //
148            // Since quote-transformer might buffer some of the
149            // nested tokens, the integrity of $ctk is compromised.
150            // Flatten it out.
151            //
152            // return $newToks;
153        }
154    }
155
156    /**
157     * @inheritDoc
158     */
159    public function onAny( $token ): ?array {
160        $this->env->trace( "quote", $this->pipelineId, "ANY | ", $token );
161        $this->currentChunk[] = $token;
162        return [];
163    }
164
165    /**
166     * Handle QUOTE tags. These are collected in italic/bold lists depending on
167     * the length of quote string. Actual analysis and conversion to the
168     * appropriate tag tokens is deferred until the next NEWLINE token triggers
169     * processQuotes.
170     */
171    private function onQuote( Token $token ): array {
172        $v = $token->getAttributeV( 'value' );
173        $qlen = strlen( $v );
174        $this->env->trace( "quote", $this->pipelineId, "QUOTE | ", $token );
175
176        $this->onAnyEnabled = true;
177
178        if ( $qlen === 2 || $qlen === 3 || $qlen === 5 ) {
179            $this->startNewChunk();
180            $this->currentChunk[] = $token;
181            $this->startNewChunk();
182        }
183
184        return [];
185    }
186
187    /**
188     * Handle explicit EOL (NlTk/EOFTk) or implicit EOL, which trigger the
189     * actual quote analysis on the collected quote tokens so far.
190     * @return ?list<string|Token>
191     */
192    private function processQuotes( ?Token $token = null ): ?array {
193        if ( !$this->onAnyEnabled ) {
194            // Nothing to do, quick abort.
195            return null;
196        }
197
198        $this->env->trace( "quote", $this->pipelineId, "NL    |", $token );
199
200        // count number of bold and italics
201        $numbold = 0;
202        $numitalics = 0;
203        $chunkCount = count( $this->chunks );
204        for ( $i = 1; $i < $chunkCount; $i += 2 ) {
205            // quote token
206            Assert::invariant( count( $this->chunks[$i] ) === 1, 'Expected a single token in the chunk' );
207            $qlen = strlen( $this->chunks[$i][0]->getAttributeV( "value" ) );
208            if ( $qlen === 2 || $qlen === 5 ) {
209                $numitalics++;
210            }
211            if ( $qlen === 3 || $qlen === 5 ) {
212                $numbold++;
213            }
214        }
215
216        // balance out tokens, convert placeholders into tags
217        if ( ( $numitalics % 2 === 1 ) && ( $numbold % 2 === 1 ) ) {
218            $firstsingleletterword = -1;
219            $firstmultiletterword = -1;
220            $firstspace = -1;
221            $chunkCount = count( $this->chunks );
222            for ( $i = 1; $i < $chunkCount; $i += 2 ) {
223                // only look at bold tags
224                if ( strlen( $this->chunks[$i][0]->getAttributeV( "value" ) ) !== 3 ) {
225                    continue;
226                }
227
228                $tok = $this->chunks[$i][0];
229                $lastCharIsSpace = $tok->getAttributeV( 'isSpace_1' );
230                $secondLastCharIsSpace = $tok->getAttributeV( 'isSpace_2' );
231                if ( $lastCharIsSpace && $firstspace === -1 ) {
232                    $firstspace = $i;
233                } elseif ( !$lastCharIsSpace ) {
234                    if ( $secondLastCharIsSpace && $firstsingleletterword === -1 ) {
235                        $firstsingleletterword = $i;
236                        // if firstsingleletterword is set, we don't need
237                        // to look at the options options, so we can bail early
238                        break;
239                    } elseif ( $firstmultiletterword === -1 ) {
240                        $firstmultiletterword = $i;
241                    }
242                }
243            }
244
245            // now see if we can convert a bold to an italic and an apostrophe
246            if ( $firstsingleletterword > -1 ) {
247                $this->convertBold( $firstsingleletterword );
248            } elseif ( $firstmultiletterword > -1 ) {
249                $this->convertBold( $firstmultiletterword );
250            } elseif ( $firstspace > -1 ) {
251                $this->convertBold( $firstspace );
252            } else {
253                // (notice that it is possible for all three to be -1 if, for
254                // example, there is only one pentuple-apostrophe in the line)
255                // In this case, do no balancing.
256            }
257        }
258
259        // convert the quote tokens into tags
260        $this->convertQuotesToTags();
261
262        // return all collected tokens including the newline
263        if ( $token ) {
264            $this->currentChunk[] = $token;
265            $this->env->trace( "quote", $this->pipelineId, "-----> ", $token );
266        }
267        $this->startNewChunk();
268
269        $res = TokenizerUtils::flattenIfArray( $this->chunks );
270
271        // prepare for next line
272        $this->reset();
273
274        return $res;
275    }
276
277    /**
278     * Convert a bold token to italic to balance an uneven number of both bold and
279     * italic tags. In the process, one quote needs to be converted back to text.
280     *
281     * @param int $i index into chunks
282     */
283    private function convertBold( int $i ): void {
284        // this should be a bold tag.
285        Assert::invariant( $i > 0 && count( $this->chunks[$i] ) === 1
286            && strlen( $this->chunks[$i][0]->getAttributeV( "value" ) ) === 3,
287            'this should be a bold tag' );
288
289        // we're going to convert it to a single plain text ' plus an italic tag
290        $this->chunks[$i - 1][] = "'";
291        $oldbold = $this->chunks[$i][0];
292        $tsr = $oldbold->dataParsoid->tsr ?? null;
293        if ( $tsr ) {
294            $tsr = new SourceRange( $tsr->start + 1, $tsr->end, $tsr->source );
295        }
296        $dp = new DataParsoid;
297        $dp->tsr = $tsr;
298        $newbold = new SelfclosingTagTk( 'mw-quote', [], $dp );
299        $newbold->setAttribute( "value", "''" ); // italic!
300        $this->chunks[$i] = [ $newbold ];
301    }
302
303    /**
304     * Convert quote tokens to tags, using the same state machine as the
305     * PHP parser uses.
306     */
307    private function convertQuotesToTags(): void {
308        $lastboth = -1;
309        $state = '';
310
311        $chunkCount = count( $this->chunks );
312        for ( $i = 1; $i < $chunkCount; $i += 2 ) {
313            Assert::invariant( count( $this->chunks[$i] ) === 1, 'expected count chunks[i] == 1' );
314            $qlen = strlen( $this->chunks[$i][0]->getAttributeV( "value" ) );
315            if ( $qlen === 2 ) {
316                if ( $state === 'i' ) {
317                    $this->quoteToTag( $i, [ new EndTagTk( 'i' ) ] );
318                    $state = '';
319                } elseif ( $state === 'bi' ) {
320                    $this->quoteToTag( $i, [ new EndTagTk( 'i' ) ] );
321                    $state = 'b';
322                } elseif ( $state === 'ib' ) {
323                    // annoying!
324                    $this->quoteToTag( $i, [
325                        new EndTagTk( 'b' ),
326                        new EndTagTk( 'i' ),
327                        new TagTk( 'b' ),
328                    ], true );
329                    $state = 'b';
330                } elseif ( $state === 'both' ) {
331                    $this->quoteToTag( $lastboth, [ new TagTk( 'b' ), new TagTk( 'i' ) ] );
332                    $this->quoteToTag( $i, [ new EndTagTk( 'i' ) ] );
333                    $state = 'b';
334                } else { // state can be 'b' or ''
335                    $this->quoteToTag( $i, [ new TagTk( 'i' ) ] );
336                    $state .= 'i';
337                }
338            } elseif ( $qlen === 3 ) {
339                if ( $state === 'b' ) {
340                    $this->quoteToTag( $i, [ new EndTagTk( 'b' ) ] );
341                    $state = '';
342                } elseif ( $state === 'ib' ) {
343                    $this->quoteToTag( $i, [ new EndTagTk( 'b' ) ] );
344                    $state = 'i';
345                } elseif ( $state === 'bi' ) {
346                    // annoying!
347                    $this->quoteToTag( $i, [
348                        new EndTagTk( 'i' ),
349                        new EndTagTk( 'b' ),
350                        new TagTk( 'i' ),
351                    ], true );
352                    $state = 'i';
353                } elseif ( $state === 'both' ) {
354                    $this->quoteToTag( $lastboth, [ new TagTk( 'i' ), new TagTk( 'b' ) ] );
355                    $this->quoteToTag( $i, [ new EndTagTk( 'b' ) ] );
356                    $state = 'i';
357                } else { // state can be 'i' or ''
358                    $this->quoteToTag( $i, [ new TagTk( 'b' ) ] );
359                    $state .= 'b';
360                }
361            } elseif ( $qlen === 5 ) {
362                if ( $state === 'b' ) {
363                    $this->quoteToTag( $i, [ new EndTagTk( 'b' ), new TagTk( 'i' ) ] );
364                    $state = 'i';
365                } elseif ( $state === 'i' ) {
366                    $this->quoteToTag( $i, [ new EndTagTk( 'i' ), new TagTk( 'b' ) ] );
367                    $state = 'b';
368                } elseif ( $state === 'bi' ) {
369                    $this->quoteToTag( $i, [ new EndTagTk( 'i' ), new EndTagTk( 'b' ) ] );
370                    $state = '';
371                } elseif ( $state === 'ib' ) {
372                    $this->quoteToTag( $i, [ new EndTagTk( 'b' ), new EndTagTk( 'i' ) ] );
373                    $state = '';
374                } elseif ( $state === 'both' ) {
375                    $this->quoteToTag( $lastboth, [ new TagTk( 'i' ), new TagTk( 'b' ) ] );
376                    $this->quoteToTag( $i, [ new EndTagTk( 'b' ), new EndTagTk( 'i' ) ] );
377                    $state = '';
378                } else { // state == ''
379                    $lastboth = $i;
380                    $state = 'both';
381                }
382            }
383        }
384
385        // now close all remaining tags.  notice that order is important.
386        if ( $state === 'both' ) {
387            $this->quoteToTag( $lastboth, [ new TagTk( 'b' ), new TagTk( 'i' ) ] );
388            $state = 'bi';
389        }
390        if ( $state === 'b' || $state === 'ib' ) {
391            $this->currentChunk[] = new EndTagTk( 'b' );
392            $this->last["b"]->dataParsoid->autoInsertedEndToken = true;
393        }
394        if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
395            $this->currentChunk[] = new EndTagTk( 'i' );
396            $this->last["i"]->dataParsoid->autoInsertedEndToken = true;
397        }
398        if ( $state === 'bi' ) {
399            $this->currentChunk[] = new EndTagTk( 'b' );
400            $this->last["b"]->dataParsoid->autoInsertedEndToken = true;
401        }
402    }
403
404    /**
405     * Convert italics/bolds into tags.
406     *
407     * @param int $chunk chunk buffer
408     * @param array $tags token
409     * @param bool $ignoreBogusTwo optional defaults to false
410     */
411    private function quoteToTag( int $chunk, array $tags, bool $ignoreBogusTwo = false ): void {
412        Assert::invariant( count( $this->chunks[$chunk] ) === 1, 'expected count chunks[i] == 1' );
413        $result = [];
414        $oldtag = $this->chunks[$chunk][0];
415        // make tsr
416        $tsr = $oldtag->dataParsoid->tsr ?? null;
417        $startpos = $tsr ? $tsr->start : null;
418        $endpos = $tsr ? $tsr->end : null;
419        $numTags = count( $tags );
420        for ( $i = 0; $i < $numTags; $i++ ) {
421            if ( $tsr ) {
422                if ( $i === 0 && $ignoreBogusTwo ) {
423                    $this->last[$tags[$i]->getName()]->dataParsoid->autoInsertedEndToken = true;
424                } elseif ( $i === 2 && $ignoreBogusTwo ) {
425                    $tags[$i]->dataParsoid->autoInsertedStartToken = true;
426                } elseif ( $tags[$i]->getName() === 'b' ) {
427                    $tags[$i]->dataParsoid->tsr = new SourceRange( $startpos, $startpos + 3, $tsr->source );
428                    $startpos = $tags[$i]->dataParsoid->tsr->end;
429                } elseif ( $tags[$i]->getName() === 'i' ) {
430                    $tags[$i]->dataParsoid->tsr = new SourceRange( $startpos, $startpos + 2, $tsr->source );
431                    $startpos = $tags[$i]->dataParsoid->tsr->end;
432                }
433            }
434            $this->last[$tags[$i]->getName()] = ( $tags[$i] instanceof EndTagTk ) ? null : $tags[$i];
435            $result[] = $tags[$i];
436        }
437        if ( $tsr ) {
438            Assert::invariant( $startpos === $endpos, 'Start: $startpos !== end: $endpos' );
439        }
440        $this->chunks[$chunk] = $result;
441    }
442}