Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.48% covered (success)
90.48%
95 / 105
88.89% covered (warning)
88.89%
16 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
ZObjectValueRenderer
90.48% covered (success)
90.48%
95 / 105
88.89% covered (warning)
88.89%
16 / 18
54.34
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 render
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 rendersWhole
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 renderText
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 renderLines
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 renderInline
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
8
 renderListLines
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 renderRecordLines
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
5
 recordKeys
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 renderMonolingual
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
5
 renderScalar
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 isLinkableKey
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 referenceLink
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 escapeMultiline
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 elision
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 isList
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 listItems
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 listItemsAreLinkable
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * WikiLambda ZObjectValueRenderer: renders a ZObject value appearing in a
4 * revision diff as readable, labelled HTML.
5 *
6 * @file
7 * @ingroup Extensions
8 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
9 * @license MIT
10 */
11
12namespace MediaWiki\Extension\WikiLambda\Diff;
13
14use MediaWiki\Extension\WikiLambda\Registry\ZTypeRegistry;
15use MediaWiki\Extension\WikiLambda\ZObjectUtils;
16use MediaWiki\Html\Html;
17use MediaWiki\Language\MessageLocalizer;
18
19/**
20 * Turns the value carried by a diff operation into HTML for a diff cell.
21 *
22 * Most diff values are leaves — a string, or a reference to another object —
23 * and render as one line. But adding or removing a whole sub-tree, or swapping
24 * a value for one of a different type, carries a nested structure, which was
25 * previously dumped as raw JSON and so was unreadable: keys and references
26 * alike appeared as bare ZIDs. Such a value is instead rendered as one
27 * "<key label>: <value>" line per key, nesting where a value needs lines of its
28 * own, and linking references to their targets.
29 *
30 * Everything is escaped here, since ZObject leaves — monolingual text, string
31 * values, implementation code — are arbitrary wiki content: only this class's
32 * own structural markup is ever raw.
33 *
34 * Output is deliberately styled with nothing but line breaks and leading
35 * spaces, so that diffs need no stylesheet of their own beyond the diff table
36 * MediaWiki already provides.
37 */
38class ZObjectValueRenderer {
39
40    /**
41     * How deeply to nest before eliding the remainder. Diff cells are narrow and
42     * a ZObject body can be arbitrarily deep, so past a few levels the structure
43     * costs more to read than it explains.
44     *
45     * Records are the unit of nesting: a list neither indents its items nor
46     * counts against this, since it introduces no labelled level of its own. A
47     * list of lists is therefore bounded by the line budget instead.
48     */
49    private const MAX_DEPTH = 3;
50
51    /**
52     * How many lines to render for one value before eliding the remainder, so
53     * that replacing a whole function body cannot flood the diff table.
54     */
55    private const MAX_LINES = 20;
56
57    /** Leading spaces marking one level of nesting. */
58    private const INDENT = "\u{00A0}\u{00A0}";
59
60    /** @var int Lines still available to the value being rendered. */
61    private int $budget = self::MAX_LINES;
62
63    public function __construct(
64        private readonly MessageLocalizer $messageLocalizer,
65        private readonly DiffLabelResolver $labels
66    ) {
67    }
68
69    /**
70     * Render a diff value as escaped HTML, as one line where it is a leaf and as
71     * a nested block of lines where it is a structure.
72     *
73     * @param mixed $value The value carried by the diff operation
74     * @param string|null $valueKey The key immediately holding it, which decides
75     *   whether a reference-shaped string may be linked; null for free text
76     * @return string
77     */
78    public function render( $value, ?string $valueKey = null ): string {
79        $this->budget = self::MAX_LINES;
80        return implode( '<br />', $this->renderLines( $value, $this->isLinkableKey( $valueKey ), 0 ) );
81    }
82
83    /**
84     * Whether a value should be shown whole rather than word-diffed against its
85     * counterpart: true for a structure, whose serialisation says nothing useful
86     * when compared character by character, and for a reference, whose ZID
87     * spelling likewise says nothing about how the target differs.
88     *
89     * @param mixed $value
90     * @param string|null $valueKey The key immediately holding the value
91     * @return bool
92     */
93    public function rendersWhole( $value, ?string $valueKey ): bool {
94        if ( is_array( $value ) ) {
95            return true;
96        }
97        return $this->isLinkableKey( $valueKey )
98            && $this->referenceLink( $this->renderText( $value ) ) !== null;
99    }
100
101    /**
102     * Render a value as plain text, for the callers that word-diff two sides
103     * against each other rather than displaying them whole.
104     *
105     * @param mixed $value
106     * @return string
107     */
108    public function renderText( $value ): string {
109        return is_string( $value ) ? $value : (string)json_encode(
110            $value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
111        );
112    }
113
114    /**
115     * @param mixed $value
116     * @param bool $linkable Whether a reference-shaped leaf here may be linked
117     * @param int $depth
118     * @return string[] Lines of escaped HTML, without indentation
119     */
120    private function renderLines( $value, bool $linkable, int $depth ): array {
121        $inline = $this->renderInline( $value, $linkable, $depth );
122        if ( $inline !== null ) {
123            $this->budget--;
124            return [ $inline ];
125        }
126
127        // Anything not renderable on one line is an array, either a typed list or
128        // a record of keys.
129        '@phan-var array $value';
130        return self::isList( $value )
131            ? $this->renderListLines( $value, $depth )
132            : $this->renderRecordLines( $value, $depth );
133    }
134
135    /**
136     * Render a value on a single line, or return null if it needs more than one.
137     *
138     * @param mixed $value
139     * @param bool $linkable
140     * @param int $depth
141     * @return string|null
142     */
143    private function renderInline( $value, bool $linkable, int $depth ): ?string {
144        if ( !is_array( $value ) ) {
145            return $this->renderScalar( $value, $linkable );
146        }
147
148        // A string object carries nothing but its text, so show just the text.
149        if ( ( $value[ZTypeRegistry::Z_OBJECT_TYPE] ?? null ) === ZTypeRegistry::Z_STRING ) {
150            return $this->renderScalar( $value[ZTypeRegistry::Z_STRING_VALUE] ?? '', false );
151        }
152
153        // A monolingual value is keyed by its language, not by its position.
154        $monolingual = $this->renderMonolingual( $value );
155        if ( $monolingual !== null ) {
156            return $monolingual;
157        }
158
159        // A list of leaves reads better run together than one item per line.
160        if ( self::isList( $value ) ) {
161            $items = self::listItems( $value );
162            $leaves = array_filter( $items, static fn ( $item ): bool => !is_array( $item ) );
163            if ( count( $leaves ) === count( $items ) ) {
164                $itemsLinkable = self::listItemsAreLinkable( $value );
165                return implode( ', ', array_map(
166                    fn ( $item ): string => $this->renderScalar( $item, $itemsLinkable ),
167                    $items
168                ) );
169            }
170        }
171
172        // Nothing fits on one line, and there is no room to nest: say how much was
173        // left rather than truncating silently, which would read as though the
174        // value were complete. Checked only here, so that a value which does fit
175        // on one line is always shown however deep it sits.
176        if ( $depth >= self::MAX_DEPTH || $this->budget < 1 ) {
177            return $this->elision( count( $value ) );
178        }
179
180        return null;
181    }
182
183    /**
184     * Render a typed list as one line per item, dropping the leading type
185     * reference, which names the type every item already declares.
186     *
187     * @param array $value
188     * @param int $depth
189     * @return string[]
190     */
191    private function renderListLines( array $value, int $depth ): array {
192        $items = self::listItems( $value );
193        $itemsLinkable = self::listItemsAreLinkable( $value );
194        $lines = [];
195        foreach ( $items as $index => $item ) {
196            if ( $this->budget < 1 ) {
197                $lines[] = $this->elision( count( $items ) - $index );
198                break;
199            }
200            $lines = array_merge( $lines, $this->renderLines( $item, $itemsLinkable, $depth ) );
201        }
202        return $lines;
203    }
204
205    /**
206     * Render a record as one "<key label>: <value>" line per key, nesting any
207     * value that needs lines of its own underneath its key.
208     *
209     * @param array $value
210     * @param int $depth
211     * @return string[]
212     */
213    private function renderRecordLines( array $value, int $depth ): array {
214        $keys = $this->recordKeys( $value );
215        $lines = [];
216        $remaining = count( $keys );
217        foreach ( $keys as $key ) {
218            if ( $this->budget < 1 ) {
219                $lines[] = $this->elision( $remaining );
220                break;
221            }
222            $remaining--;
223
224            $label = htmlspecialchars( $this->labels->getKeyLabel( $key ) ) . ':';
225            $valueLines = $this->renderLines( $value[$key], $this->isLinkableKey( $key ), $depth + 1 );
226            if ( count( $valueLines ) === 1 ) {
227                $lines[] = $label . ' ' . $valueLines[0];
228                continue;
229            }
230
231            // A multi-line value goes under its key rather than beside it.
232            $lines[] = $label;
233            foreach ( $valueLines as $line ) {
234                $lines[] = self::INDENT . $line;
235            }
236        }
237        return $lines;
238    }
239
240    /**
241     * The keys of a record worth showing. The type is dropped when it is a plain
242     * reference, since a homogeneous list repeats it on every item and a labelled
243     * key already says what the value is; it is kept when it is itself a
244     * structure, as a generic type such as "list of strings" is informative.
245     *
246     * @param array $value
247     * @return string[]
248     */
249    private function recordKeys( array $value ): array {
250        $keys = array_map( 'strval', array_keys( $value ) );
251        $type = $value[ZTypeRegistry::Z_OBJECT_TYPE] ?? null;
252        return ( $type !== null && !is_array( $type ) )
253            ? array_values( array_diff( $keys, [ ZTypeRegistry::Z_OBJECT_TYPE ] ) )
254            : $keys;
255    }
256
257    /**
258     * Render a monolingual string or string set as "<language>: <text>", or null
259     * if this is not one.
260     *
261     * @param array $value
262     * @return string|null
263     */
264    private function renderMonolingual( array $value ): ?string {
265        $type = $value[ZTypeRegistry::Z_OBJECT_TYPE] ?? null;
266        if ( $type === ZTypeRegistry::Z_MONOLINGUALSTRING ) {
267            $languageZid = $value[ZTypeRegistry::Z_MONOLINGUALSTRING_LANGUAGE] ?? null;
268            $text = $this->renderText( $value[ZTypeRegistry::Z_MONOLINGUALSTRING_VALUE] ?? '' );
269        } elseif ( $type === ZTypeRegistry::Z_MONOLINGUALSTRINGSET ) {
270            $languageZid = $value[ZTypeRegistry::Z_MONOLINGUALSTRINGSET_LANGUAGE] ?? null;
271            $strings = self::listItems( $value[ZTypeRegistry::Z_MONOLINGUALSTRINGSET_VALUE] ?? [] );
272            $text = implode( ', ', array_filter( $strings, 'is_string' ) );
273        } else {
274            return null;
275        }
276
277        $name = is_string( $languageZid ) ? $this->labels->getLanguage( $languageZid )['name'] : null;
278        $escaped = $this->escapeMultiline( $text );
279        return $name === null ? $escaped : htmlspecialchars( $name ) . ': ' . $escaped;
280    }
281
282    /**
283     * Render a leaf: a reference in a linkable position becomes a link to its
284     * target, and anything else becomes escaped text.
285     *
286     * @param mixed $value
287     * @param bool $linkable
288     * @return string
289     */
290    private function renderScalar( $value, bool $linkable ): string {
291        $text = $this->renderText( $value );
292        return ( $linkable ? $this->referenceLink( $text ) : null )
293            ?? $this->escapeMultiline( $text );
294    }
295
296    /**
297     * Whether a reference-shaped value held under a key may be linked to its
298     * target.
299     *
300     * Free-text values (monolingual strings, aliases) sit under no key we can
301     * judge, and must never be linked, even when their text happens to look like
302     * a ZID. Neither may values under keys holding literal content: Z6K1 (a
303     * string's value) is the key case and is not in the shared ignore list, so it
304     * is guarded explicitly alongside that list.
305     *
306     * @param string|null $key
307     * @return bool
308     */
309    public function isLinkableKey( ?string $key ): bool {
310        return $key !== null
311            && $key !== ZTypeRegistry::Z_STRING_VALUE
312            && !in_array( $key, ZTypeRegistry::IGNORE_KEY_VALUES_FOR_LABELLING, true );
313    }
314
315    /**
316     * Render a reference as a link to the referenced object's page, labelled
317     * "<label> (<zid>)" (or just the linked id when no label is known). Returns
318     * null for non-references and for ids with no valid target.
319     *
320     * @param string $value
321     * @return string|null
322     */
323    private function referenceLink( string $value ): ?string {
324        if ( !ZObjectUtils::isValidZObjectReference( $value ) ) {
325            return null;
326        }
327
328        $reference = $this->labels->getReference( $value );
329        if ( $reference === null ) {
330            return null;
331        }
332
333        $label = $reference['label'] ?? null;
334        $text = ( $label === null || $label === '' )
335            ? $value
336            : $label . ' (' . $value . ')';
337        return Html::element( 'a', [ 'href' => $reference['url'] ], $text );
338    }
339
340    /**
341     * Escape text for HTML, turning newlines into visible line breaks.
342     *
343     * @param string $text
344     * @return string
345     */
346    public function escapeMultiline( string $text ): string {
347        return implode( '<br />', array_map( 'htmlspecialchars', explode( "\n", $text ) ) );
348    }
349
350    /**
351     * The marker standing in for the part of a value that was not rendered.
352     *
353     * The count is of the entries elided at this point — the remaining items of
354     * this list, or keys of this record — rather than of everything below them,
355     * which would mean walking the very structure being skipped.
356     *
357     * @param int $count
358     * @return string
359     */
360    private function elision( int $count ): string {
361        return htmlspecialchars(
362            $this->messageLocalizer->msg( 'wikilambda-diff-value-elided' )->numParams( $count )->text()
363        );
364    }
365
366    /**
367     * Whether an array is a typed list rather than a record of keys.
368     *
369     * @param array $value
370     * @return bool
371     */
372    private static function isList( array $value ): bool {
373        foreach ( $value as $key => $unused ) {
374            if ( is_string( $key ) ) {
375                return false;
376            }
377        }
378        return true;
379    }
380
381    /**
382     * The items of a typed list, without the leading reference to the type of
383     * its items.
384     *
385     * @param mixed $value
386     * @return array
387     */
388    private static function listItems( $value ): array {
389        return is_array( $value ) ? array_values( array_slice( $value, 1 ) ) : [];
390    }
391
392    /**
393     * Whether a typed list's items may be linked. Items sit at numeric indices,
394     * which say nothing either way, so judge by the list's own declared item
395     * type: a list of references may be linked, whereas a list of strings — the
396     * strings of an alias set, say — holds literal text and may not.
397     *
398     * @param array $value
399     * @return bool
400     */
401    private static function listItemsAreLinkable( array $value ): bool {
402        return ( $value[0] ?? null ) !== ZTypeRegistry::Z_STRING;
403    }
404}