Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 164
0.00% covered (danger)
0.00%
0 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
LanguageVariantHandler
0.00% covered (danger)
0.00%
0 / 164
0.00% covered (danger)
0.00%
0 / 6
3540
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
 convertOne
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
2
 emptyFrag
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 compressSpArray
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
42
 onLanguageVariant
0.00% covered (danger)
0.00%
0 / 127
0.00% covered (danger)
0.00%
0 / 1
2352
 onTag
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid\Wt2Html\TT;
5
6use Wikimedia\Parsoid\Core\SourceRange;
7use Wikimedia\Parsoid\DOM\DocumentFragment;
8use Wikimedia\Parsoid\NodeData\DataMwVariant;
9use Wikimedia\Parsoid\NodeData\DataParsoid;
10use Wikimedia\Parsoid\NodeData\VariantFilter;
11use Wikimedia\Parsoid\NodeData\VariantOneWay;
12use Wikimedia\Parsoid\NodeData\VariantTwoWay;
13use Wikimedia\Parsoid\Tokens\EndTagTk;
14use Wikimedia\Parsoid\Tokens\EOFTk;
15use Wikimedia\Parsoid\Tokens\KV;
16use Wikimedia\Parsoid\Tokens\TagTk;
17use Wikimedia\Parsoid\Tokens\Token;
18use Wikimedia\Parsoid\Tokens\VariantOption;
19use Wikimedia\Parsoid\Tokens\XMLTagTk;
20use Wikimedia\Parsoid\Utils\DOMUtils;
21use Wikimedia\Parsoid\Utils\PHPUtils;
22use Wikimedia\Parsoid\Utils\PipelineUtils;
23use Wikimedia\Parsoid\Wikitext\Consts;
24use Wikimedia\Parsoid\Wt2Html\TokenHandlerPipeline;
25
26/**
27 * Handler for language conversion markup, which looks like `-{ ... }-`.
28 */
29class LanguageVariantHandler extends XMLTagBasedHandler {
30    /** @inheritDoc */
31    public function __construct( TokenHandlerPipeline $manager, array $options ) {
32        parent::__construct( $manager, $options );
33    }
34
35    /**
36     * convert one variant text to dom.
37     *
38     * @param TokenHandlerPipeline $manager
39     * @param array $options
40     * @param string $t
41     * @param array $attribs
42     *
43     * @return array{frag: DocumentFragment, isBlock: bool}
44     */
45    private function convertOne( TokenHandlerPipeline $manager, array $options, string $t,
46        array $attribs ): array {
47        // we're going to fetch the actual token list from attribs
48        // (this ensures that it has gone through the earlier stages
49        // of the pipeline already to be expanded)
50        $t = PHPUtils::stripPrefix( $t, 'mw:lv' );
51        $srcOffsets = $attribs[$t]->srcOffsets;
52        $domFragment = PipelineUtils::processContentInPipeline(
53            $this->env, $manager->getFrame(), array_merge( $attribs[$t]->v, [ new EOFTk() ] ),
54            [
55                'pipelineType' => 'expanded-tokens-to-fragment',
56                'pipelineOpts' => [
57                    'inlineContext' => true,
58                    'expandTemplates' => $options['expandTemplates'],
59                    'inTemplate' => $options['inTemplate']
60                ],
61                'srcOffsets' => $srcOffsets->value ?? null,
62                'sol' => true
63            ]
64        );
65        return [
66            'frag' => $domFragment,
67            'isBlock' => DOMUtils::hasBlockElementDescendant( $domFragment ),
68        ];
69    }
70
71    private function emptyFrag(): DocumentFragment {
72        $doc = $this->env->getTopLevelDoc();
73        return $doc->createDocumentFragment();
74    }
75
76    /**
77     * Compress a whitespace sequence.
78     * @see \Wikimedia\Parsoid\Html2Wt\LanguageVariantHandler::expandSpArrary
79     * @param ?list<string> $a
80     * @return ?list<int|string>
81     */
82    private function compressSpArray( ?array $a ): ?array {
83        $result = [];
84        $ctr = 0;
85        if ( $a === null ) {
86            return $a;
87        }
88        foreach ( $a as $sp ) {
89            if ( $sp === '' ) {
90                $ctr++;
91            } else {
92                if ( $ctr > 0 ) {
93                    $result[] = $ctr;
94                    $ctr = 0;
95                }
96                $result[] = $sp;
97            }
98        }
99        if ( $ctr > 0 ) {
100            $result[] = $ctr;
101        }
102        return $result;
103    }
104
105    /**
106     * Main handler.
107     * See {@link TokenHandlerPipeline#addTransform}'s transformation parameter
108     * @param Token $token
109     * @return ?array<string|Token>
110     */
111    private function onLanguageVariant( Token $token ): ?array {
112        $manager = $this->manager;
113        $options = $this->options;
114        $attribs = $token->attribs;
115        $dataParsoid = $token->dataParsoid;
116        $tsr = $dataParsoid->tsr;
117        $variantInfo = $dataParsoid->getTemp()->variantInfo;
118        $flags = $variantInfo->flags;
119        $flagSp = $variantInfo->flagSp;
120        $variantTexts = $variantInfo->texts;
121        $sawFlagA = false;
122
123        // remove trailing semicolon marker, if present
124        $trailingSemi = false;
125        if ( count( $variantTexts ) &&
126            ( $variantTexts[count( $variantTexts ) - 1]->semi )
127        ) {
128            $trailingSemi = array_pop( $variantTexts )->sp[0];
129        }
130        // convert all variant texts to DOM
131        $isBlock = false;
132        $texts = array_map( function ( VariantOption $t ) use ( $manager, $options, $attribs, &$isBlock ) {
133            if ( $t->twoway ) {
134                $text = $this->convertOne( $manager, $options, $t->text, $attribs );
135                $isBlock = $isBlock || !empty( $text['isBlock'] );
136                return [ 'lang' => $t->lang, 'text' => $text['frag'], 'twoway' => true, 'sp' => $t->sp ];
137            } elseif ( $t->lang !== null ) {
138                $from = $this->convertOne( $manager, $options, $t->from, $attribs );
139                $to = $this->convertOne( $manager, $options, $t->to, $attribs );
140                $isBlock = $isBlock || !empty( $from['isBlock'] ) || !empty( $to['isBlock'] );
141                return [ 'lang' => $t->lang, 'from' => $from['frag'], 'to' => $to['frag'],
142                    'sp' => $t->sp ];
143            } else {
144                $text = $this->convertOne( $manager, $options, $t->text, $attribs );
145                $isBlock = $isBlock || !empty( $text['isBlock'] );
146                return [ 'text' => $text['frag'], 'sp' => [] ];
147            }
148        }, $variantTexts );
149        // collect two-way/one-way conversion rules
150        $oneway = [];
151        $twoway = [];
152        $sawTwoway = false;
153        $sawOneway = false;
154        $textSp = null;
155        $twowaySp = [];
156        $onewaySp = [];
157        foreach ( $texts as $t ) {
158            if ( isset( $t['twoway'] ) ) {
159                $twoway[] = new VariantTwoWay( $t['lang'], $t['text'] );
160                array_push( $twowaySp, $t['sp'][0], $t['sp'][1], $t['sp'][2] );
161                $sawTwoway = true;
162            } elseif ( isset( $t['lang'] ) ) {
163                $oneway[] = new VariantOneWay( $t['lang'], $t['from'], $t['to'] );
164                array_push( $onewaySp, $t['sp'][0], $t['sp'][1], $t['sp'][2], $t['sp'][3] );
165                $sawOneway = true;
166            }
167        }
168
169        $dataMWV = new DataMwVariant;
170        $sawDisabled = false;
171        $sawName = false;
172        if ( count( $flags ) === 0 && count( $variantInfo->variants ) > 0 ) {
173            // "Restrict possible variants to a limited set"
174            $dataMWV->filter = new VariantFilter( $variantInfo->variants, $texts[0]['text'] );
175            $dataMWV->show = true;
176        } else {
177            foreach ( $flags as $f ) {
178                $flagName = Consts::$LCFlagMap[$f] ?? null;
179                if ( $flagName === null ) {
180                    $dataMWV->error = true;
181                } elseif ( $flagName === 'disabled' ) {
182                    $sawDisabled = true;
183                } elseif ( $flagName === 'name' ) {
184                    $sawName = true;
185                } elseif ( $flagName ) {
186                    $dataMWV->$flagName = true;
187                    if ( $f === 'A' ) {
188                        $sawFlagA = true;
189                    }
190                }
191            }
192            // (this test is done at the top of ConverterRule::getRuleConvertedStr)
193            // (also partially in ConverterRule::parse)
194            if ( count( $texts ) === 1 &&
195                !isset( $texts[0]['lang'] ) && !$sawName
196            ) {
197                if ( $dataMWV->add || $dataMWV->remove ) {
198                    $variants = [ '*' ];
199                    $twoway = array_map( static function ( string $code ) use ( $texts, &$sawTwoway ) {
200                        $sawTwoway = true;
201                        return new VariantTwoWay( $code, $texts[0]['text'] );
202                    }, $variants );
203                } else {
204                    $sawDisabled = true;
205                    $dataMWV->describe = false;
206                }
207            }
208            if ( $dataMWV->describe ) {
209                if ( !$sawFlagA ) {
210                    $dataMWV->show = true;
211                }
212            }
213            if ( $sawDisabled || $sawName ) {
214                if ( $sawDisabled ) {
215                    $dataMWV->disabled = $texts[0]['text'] ?? $this->emptyFrag();
216                } else {
217                    $dataMWV->name = $texts[0]['text'] ?? $this->emptyFrag();
218                }
219                if ( $dataMWV->title || $dataMWV->add ) {
220                    $dataMWV->show = false;
221                } else {
222                    $dataMWV->show = true;
223                }
224            } elseif ( $sawTwoway ) {
225                $dataMWV->twoway = $twoway;
226                $textSp = $twowaySp;
227                if ( $sawOneway ) {
228                    $dataMWV->error = true;
229                }
230            } else {
231                $dataMWV->oneway = $oneway;
232                $textSp = $onewaySp;
233                if ( !$sawOneway ) {
234                    $dataMWV->error = true;
235                }
236            }
237        }
238        // Use meta/not meta instead of explicit 'show' flag.
239        $isMeta = !$dataMWV->show;
240        $dataMWV->show = false;
241        // Trim some data from data-parsoid if it matches the defaults
242        if ( count( $flagSp ) === 2 * count( $variantInfo->original ) ) {
243            $result = true;
244            foreach ( $flagSp as $s ) {
245                if ( $s !== '' ) {
246                    $result = false;
247                    break;
248                }
249            }
250            if ( $result ) {
251                $flagSp = null;
252            }
253        }
254        if ( $trailingSemi !== false && $textSp ) {
255            $textSp[] = $trailingSemi;
256        }
257
258        // Our markup is always the same, except for the contents of
259        // the data-mw-variant attribute and whether it's a span, div, or a
260        // meta, depending on (respectively) whether conversion output
261        // contains only inline content, could contain block content,
262        // or never contains any content.
263
264        $das = new DataParsoid;
265        $das->fl = $variantInfo->original; // original "fl"ags
266        $flSp = $this->compressSpArray( $flagSp ); // spaces around flags
267        if ( $flSp !== null ) {
268            $das->flSp = $flSp;
269        }
270        $das->src = $dataParsoid->src;
271        $tSp = $this->compressSpArray( $textSp ); // spaces around texts
272        if ( $tSp !== null ) {
273            $das->tSp = $tSp;
274        }
275        $das->tsr = new SourceRange( $tsr->start, $isMeta ? $tsr->end : ( $tsr->end - 2 ), $tsr->source );
276        // Tunnel DataMwVariant through the token inside the DataParsoid
277        $das->getTemp()->variantData = $dataMWV;
278
279        $tokens = [
280            new TagTk( $isMeta ? 'meta' : ( $isBlock ? 'div' : 'span' ), [
281                    new KV( 'typeof', 'mw:LanguageVariant' ),
282            ], $das
283            )
284        ];
285        if ( !$isMeta ) {
286            $metaDP = new DataParsoid;
287            $metaDP->tsr = new SourceRange( $tsr->end - 2, $tsr->end, $tsr->source );
288            $tokens[] = new EndTagTk( $isBlock ? 'div' : 'span', [], $metaDP );
289        }
290
291        return $tokens;
292    }
293
294    /**
295     * @inheritDoc
296     */
297    public function onTag( XMLTagTk $token ): ?array {
298        return $token->getName() === 'language-variant' ? $this->onLanguageVariant( $token ) : null;
299    }
300}