Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
92.16% covered (success)
92.16%
47 / 51
75.00% covered (warning)
75.00%
6 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
DiffLabelResolver
92.16% covered (success)
92.16%
47 / 51
75.00% covered (warning)
75.00%
6 / 8
25.30
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
 prefetch
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
7
 getKeyLabel
62.50% covered (warning)
62.50%
5 / 8
0.00% covered (danger)
0.00%
0 / 1
4.84
 getReference
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 getLanguage
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 resolveLanguage
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 getLabel
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 fetchDefinition
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
4.07
1<?php
2/**
3 * WikiLambda DiffLabelResolver: resolves the ZObject identifiers that appear in
4 * a revision diff — keys, references and languages — to display text.
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\ZLangRegistry;
15use MediaWiki\Extension\WikiLambda\ZObjectContent\ZObjectContent;
16use MediaWiki\Extension\WikiLambda\ZObjects\ZPersistentObject;
17use MediaWiki\Extension\WikiLambda\ZObjectStore;
18use MediaWiki\Extension\WikiLambda\ZObjectUtils;
19use MediaWiki\Language\Language;
20use MediaWiki\Language\LanguageFactory;
21use MediaWiki\Title\TitleFactory;
22
23/**
24 * A ZObject diff needs three kinds of display text, all derived from ZIDs and
25 * all wanted in the viewer's language:
26 *
27 * - the label of a key (e.g. "Z8K1" → "arguments"), for path breadcrumbs;
28 * - the label and page URL of a referenced object (e.g. "Z40" → "Boolean"), so
29 *   reference-valued changes can render as links;
30 * - the name, BCP-47 code and writing direction of a language (e.g. "Z1002" →
31 *   English/en/ltr), so language-specific values render in their own script.
32 *
33 * All three are gathered here rather than passed around as separate callables,
34 * because they share both a lifetime (one diff render) and a cache: the same
35 * handful of standard types and languages recur across many rows, and every
36 * lookup is a database read. Every method memoises, and degrades to the raw ZID
37 * rather than throwing, so an unresolvable identifier costs a reader clarity
38 * but never the whole diff.
39 */
40class DiffLabelResolver {
41
42    /**
43     * Matches a global key such as "Z8K1", capturing the ZID of the type or
44     * function that defines it and therefore holds its label.
45     */
46    private const GLOBAL_KEY_PATTERN = '/^(Z\d+)K\d+$/';
47
48    /** @var array<string,?ZPersistentObject> Memoised zid => definition (null when unresolved) */
49    private array $definitions = [];
50
51    /** @var array<string,?string> Memoised zid => label in the viewer's language (null when it has none) */
52    private array $labels = [];
53
54    /** @var array<string,?array> Memoised zid => reference label and URL (null when no valid target) */
55    private array $references = [];
56
57    /** @var array<string,array> Memoised zid => language name, code and direction */
58    private array $languages = [];
59
60    public function __construct(
61        private readonly ZObjectStore $zObjectStore,
62        private readonly Language $language,
63        private readonly LanguageFactory $languageFactory,
64        private readonly TitleFactory $titleFactory,
65        private readonly ZLangRegistry $langRegistry
66    ) {
67    }
68
69    /**
70     * Warm the caches for a batch of identifiers, so that rendering a whole diff
71     * costs a fixed number of database reads rather than one or two per row.
72     *
73     * Identifiers are sorted by shape: a global key needs the whole owning type
74     * or function definition, because its label lives in that definition's key
75     * list, while a plain reference needs only its own label from the secondary
76     * label table. Anything else — a list index, a bare local key, free text — is
77     * ignored.
78     *
79     * Callers need not be exhaustive: whatever is missed simply falls back to an
80     * individual read on first use. In particular the language of a changed
81     * monolingual value is found by navigating the surrounding object rather than
82     * from the diff itself, so it is usually resolved individually.
83     *
84     * @param string[] $identifiers Keys and references appearing in the diff, in
85     *   any order and with any number of duplicates
86     */
87    public function prefetch( array $identifiers ): void {
88        $keyOwners = [];
89        $references = [];
90        foreach ( array_unique( $identifiers ) as $identifier ) {
91            if ( preg_match( self::GLOBAL_KEY_PATTERN, $identifier, $matches ) ) {
92                $keyOwners[$matches[1]] = true;
93            } elseif ( ZObjectUtils::isValidZObjectReference( $identifier ) ) {
94                $references[$identifier] = true;
95            }
96        }
97
98        // Only ask for what is not already cached, so that a second call after
99        // more identifiers come to light does not re-read the first batch.
100        // array_diff() preserves keys, so reindex: these become query IN lists.
101        $keyOwners = array_values( array_diff( array_keys( $keyOwners ), array_keys( $this->definitions ) ) );
102        if ( $keyOwners !== [] ) {
103            $definitions = $this->zObjectStore->fetchBatchZObjects( $keyOwners );
104            foreach ( $keyOwners as $zid ) {
105                $this->definitions[$zid] = $definitions[$zid] ?? null;
106            }
107        }
108
109        // A language's display name is just the label of its ZLanguage object, so
110        // languages and references share this cache.
111        $references = array_values( array_diff( array_keys( $references ), array_keys( $this->labels ) ) );
112        if ( $references !== [] ) {
113            $this->labels += $this->zObjectStore->fetchZObjectLabels(
114                $references, $this->language->getCode()
115            );
116        }
117    }
118
119    /**
120     * Resolve a key to its human-readable label, or return the key itself if it
121     * is not a global key or cannot be resolved.
122     *
123     * WikiLambda keys are globally namespaced, so the owning type or function
124     * definition is derivable from the key string alone — no surrounding context
125     * is needed. Anything that is not a global key (a list index, or a bare local
126     * key such as "K1") is returned unchanged; labelling local keys, which needs
127     * the enclosing object's type, is left for a follow-up.
128     *
129     * @param string $key
130     * @return string
131     */
132    public function getKeyLabel( string $key ): string {
133        if ( !preg_match( self::GLOBAL_KEY_PATTERN, $key, $matches ) ) {
134            return $key;
135        }
136
137        $definition = $this->fetchDefinition( $matches[1] );
138        if ( $definition === null ) {
139            return $key;
140        }
141
142        // getLabelOfGlobalKey already returns the raw key id when it cannot
143        // resolve a label; guard against unexpected structures too.
144        try {
145            return ZObjectUtils::getLabelOfGlobalKey( $key, $definition, $this->language );
146        } catch ( \Exception ) {
147            return $key;
148        }
149    }
150
151    /**
152     * Resolve a referenced ZObject id to its label and view-page URL, so diff
153     * values that are references can render as links. Returns null when the id
154     * has no valid target, and a null label when the target has none in the
155     * viewer's language.
156     *
157     * @param string $zid
158     * @return array{label:?string,url:string}|null
159     */
160    public function getReference( string $zid ): ?array {
161        if ( !array_key_exists( $zid, $this->references ) ) {
162            $title = $this->titleFactory->newFromText( $zid, NS_MAIN );
163            $this->references[$zid] = $title === null ? null : [
164                'label' => $this->getLabel( $zid ),
165                'url' => $title->getLocalURL(),
166            ];
167        }
168        return $this->references[$zid];
169    }
170
171    /**
172     * Resolve a language ZObject id to its display name (from WikiLambda's own
173     * labels, in the viewer's language) plus the BCP-47 code and writing
174     * direction, so language-specific values can be tagged with lang/dir.
175     * Degrades to the id and an undirected value.
176     *
177     * @param string $languageZid
178     * @return array{name:string,code:string,dir:string}
179     */
180    public function getLanguage( string $languageZid ): array {
181        if ( !array_key_exists( $languageZid, $this->languages ) ) {
182            $this->languages[$languageZid] = $this->resolveLanguage( $languageZid );
183        }
184        return $this->languages[$languageZid];
185    }
186
187    /**
188     * @param string $languageZid
189     * @return array{name:string,code:string,dir:string}
190     */
191    private function resolveLanguage( string $languageZid ): array {
192        $name = $this->getLabel( $languageZid ) ?? $languageZid;
193        try {
194            $code = $this->langRegistry->getLanguageCodeFromZid( $languageZid );
195            $dir = $this->languageFactory->getLanguage( $code )->getDir();
196        } catch ( \Exception ) {
197            return [ 'name' => $name, 'code' => '', 'dir' => 'auto' ];
198        }
199        return [ 'name' => $name, 'code' => $code, 'dir' => $dir ];
200    }
201
202    /**
203     * Fetch (and memoise) the label of a ZID in the viewer's language, or null if
204     * it has none in that language or its fallback chain.
205     *
206     * @param string $zid
207     * @return string|null
208     */
209    private function getLabel( string $zid ): ?string {
210        if ( !array_key_exists( $zid, $this->labels ) ) {
211            $this->labels[$zid] = $this->zObjectStore->fetchZObjectLabel( $zid, $this->language->getCode() );
212        }
213        return $this->labels[$zid];
214    }
215
216    /**
217     * Fetch (and memoise) the persisted definition for a ZID, or null if it is
218     * missing or invalid.
219     *
220     * @param string $zid
221     * @return ZPersistentObject|null
222     */
223    private function fetchDefinition( string $zid ): ?ZPersistentObject {
224        if ( !array_key_exists( $zid, $this->definitions ) ) {
225            $content = $this->zObjectStore->fetchZObject( $zid );
226            $this->definitions[$zid] = ( $content instanceof ZObjectContent && $content->isValid() )
227                ? $content->getZObject()
228                : null;
229        }
230        return $this->definitions[$zid];
231    }
232}