Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
18.13% covered (danger)
18.13%
33 / 182
8.11% covered (danger)
8.11%
3 / 37
CRAP
0.00% covered (danger)
0.00%
0 / 1
StubMetadataCollector
18.13% covered (danger)
18.13%
33 / 182
8.11% covered (danger)
8.11%
3 / 37
3503.51
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 addCategory
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 addWarningMsg
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 addExternalLink
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 getExternalLinks
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setOutputFlag
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 appendOutputStrings
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 setUnsortedPageProperty
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setNumericPageProperty
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 setExtensionData
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setJsConfigVar
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 appendExtensionData
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 appendJsConfigVar
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 addModules
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 addModuleStyles
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setLimitReportData
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setTOCData
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 addLink
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
 addImage
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 addLanguageLink
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 addTemplate
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 getLinkList
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
156
 collect
54.05% covered (warning)
54.05%
20 / 37
0.00% covered (danger)
0.00%
0 / 1
33.01
 get
60.00% covered (warning)
60.00%
9 / 15
0.00% covered (danger)
0.00%
0 / 1
8.30
 getModules
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getModuleStyles
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getJsConfigVars
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 getCategoryNames
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 getCategorySortKey
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 getPageProperty
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getExtensionData
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getOutputFlags
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 getTOCData
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setIndicator
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getIndicators
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 linkToString
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 stringToLink
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3declare( strict_types = 1 );
4
5namespace Wikimedia\Parsoid\Config;
6
7use Psr\Log\LoggerInterface;
8use Psr\Log\LogLevel;
9use Wikimedia\Assert\UnreachableException;
10use Wikimedia\Parsoid\Core\ContentMetadataCollector;
11use Wikimedia\Parsoid\Core\ContentMetadataCollectorCompat;
12use Wikimedia\Parsoid\Core\ContentMetadataCollectorStringSets as CMCSS;
13use Wikimedia\Parsoid\Core\LinkTarget;
14use Wikimedia\Parsoid\Core\MergeStrategy;
15use Wikimedia\Parsoid\Core\TOCData;
16use Wikimedia\Parsoid\Utils\TitleValue;
17
18/**
19 * Minimal implementation of a ContentMetadataCollector which just
20 * records all metadata in an array.  Used for testing or operation
21 * in API mode.
22 */
23class StubMetadataCollector implements ContentMetadataCollector {
24    use ContentMetadataCollectorCompat;
25
26    public const LINKTYPE_CATEGORY = 'category';
27    public const LINKTYPE_LANGUAGE = 'language';
28    public const LINKTYPE_INTERWIKI = 'interwiki';
29    public const LINKTYPE_LOCAL = 'local';
30    public const LINKTYPE_MEDIA = 'media';
31    public const LINKTYPE_SPECIAL = 'special';
32    public const LINKTYPE_TEMPLATE = 'template';
33
34    /** @var SiteConfig */
35    private $siteConfig;
36
37    /** @var LoggerInterface */
38    private $logger;
39
40    /** @var array<string,array> */
41    private $mWarningMsgs = [];
42
43    /** @var array */
44    private $storage = [];
45
46    /** @var string */
47    private const MERGE_STRATEGY_KEY = '_parsoid-strategy_';
48
49    /**
50     * Non-standard merge strategy to use for properties which are *not*
51     * accumulators: "write-once" means that the property should be set
52     * once (although subsequently resetting it to the same value is ok)
53     * and an error will be thrown if there is an attempt to combine
54     * multiple values.
55     *
56     * This strategy is internal to the StubMetadataCollector for now;
57     * ParserOutput implements similar semantics for many of its properties,
58     * but not (yet) in a principled or uniform way.
59     */
60    private const MERGE_STRATEGY_WRITE_ONCE = 'write-once';
61
62    /**
63     * @param SiteConfig $siteConfig Used to resolve title namespaces
64     *  and to log warnings for unsafe metadata updates
65     */
66    public function __construct(
67        SiteConfig $siteConfig
68    ) {
69        $this->siteConfig = $siteConfig;
70        $this->logger = $siteConfig->getLogger();
71    }
72
73    /** @inheritDoc */
74    public function addCategory( $c, $sort = '' ): void {
75        // Numeric strings often become an `int` when passed to addCategory()
76        $this->collect(
77            self::LINKTYPE_CATEGORY,
78            $this->linkToString( $c ),
79            $sort,
80            self::MERGE_STRATEGY_WRITE_ONCE
81        );
82    }
83
84    /** @inheritDoc */
85    public function addWarningMsg( string $msg, ...$args ): void {
86        if ( isset( $this->mWarningMsgs[$msg] ) ) {
87            // Destructive update; this is discouraged because it
88            // disables selective update.
89            $this->setOutputFlag( 'prevent-selective-update' );
90        }
91        $this->mWarningMsgs[$msg] = $args;
92    }
93
94    /** @inheritDoc */
95    public function addExternalLink( string $url ): void {
96        $this->collect(
97            'externallinks',
98            $url,
99            '',
100            self::MERGE_STRATEGY_WRITE_ONCE
101        );
102    }
103
104    public function getExternalLinks(): array {
105        return array_keys( $this->get( 'externallinks' ) );
106    }
107
108    /** @inheritDoc */
109    public function setOutputFlag( string $name, bool $val = true ): void {
110        $this->collect( 'outputflags', $name, (string)$val, self::MERGE_STRATEGY_WRITE_ONCE );
111    }
112
113    /** @inheritDoc */
114    public function appendOutputStrings( string $name, array $value ): void {
115        foreach ( $value as $v ) {
116            $this->collect( 'outputstrings', $name, $v );
117        }
118    }
119
120    /** @inheritDoc */
121    public function setUnsortedPageProperty( string $propName, string $value = '' ): void {
122        $this->collect( 'properties', $propName, $value, self::MERGE_STRATEGY_WRITE_ONCE );
123    }
124
125    /** @inheritDoc */
126    public function setNumericPageProperty( string $propName, $numericValue ): void {
127        if ( !is_numeric( $numericValue ) ) {
128            throw new \TypeError( __METHOD__ . " with non-numeric value" );
129        }
130        $value = 0 + $numericValue; # cast to number
131        $this->collect( 'properties', $propName, $value, self::MERGE_STRATEGY_WRITE_ONCE );
132    }
133
134    /** @inheritDoc */
135    public function setExtensionData( string $key, $value ): void {
136        $this->collect( 'extensiondata', $key, $value, self::MERGE_STRATEGY_WRITE_ONCE );
137    }
138
139    /** @inheritDoc */
140    public function setJsConfigVar( string $key, $value ): void {
141        $this->collect( 'jsconfigvars', $key, $value, self::MERGE_STRATEGY_WRITE_ONCE );
142    }
143
144    /** @inheritDoc */
145    public function appendExtensionData(
146        string $key,
147        $value,
148        string|MergeStrategy $strategy = MergeStrategy::UNION
149    ): void {
150        $this->collect( 'extensiondata', $key, $value, $strategy );
151    }
152
153    /** @inheritDoc */
154    public function appendJsConfigVar(
155        string $key,
156        string|int $value,
157        string|MergeStrategy $strategy = MergeStrategy::UNION
158    ): void {
159        $this->collect( 'jsconfigvars', $key, $value, $strategy );
160    }
161
162    /** @inheritDoc */
163    public function addModules( array $modules ): void {
164        $this->appendOutputStrings( CMCSS::MODULE, $modules );
165    }
166
167    /** @inheritDoc */
168    public function addModuleStyles( array $moduleStyles ): void {
169        $this->appendOutputStrings( CMCSS::MODULE_STYLE, $moduleStyles );
170    }
171
172    /** @inheritDoc */
173    public function setLimitReportData( string $key, $value ): void {
174        // XXX maybe need to JSON-encode $value
175        $this->collect( 'limitreportdata', $key, $value, self::MERGE_STRATEGY_WRITE_ONCE );
176    }
177
178    /** @inheritDoc */
179    public function setTOCData( TOCData $tocData ): void {
180        $this->collect( 'tocdata', '', $tocData, self::MERGE_STRATEGY_WRITE_ONCE );
181    }
182
183    /** @inheritDoc */
184    public function addLink( LinkTarget $link, $id = null ): void {
185        # Fragments are stripped when collecting.
186        $link = $link->removeFragmentTarget();
187        $type = self::LINKTYPE_LOCAL;
188
189        if ( $link->isExternal() ) {
190            $type = self::LINKTYPE_INTERWIKI;
191        } elseif ( $link->inNamespace( -1 ) ) {
192            $type = self::LINKTYPE_SPECIAL;
193        }
194
195        if ( $type === self::LINKTYPE_LOCAL && $link->getDbkey() === '' ) {
196            // Don't record self links - [[#Foo]]
197            return;
198        }
199        $this->collect(
200            $type,
201            $this->linkToString( $link ),
202            '',
203            self::MERGE_STRATEGY_WRITE_ONCE
204        );
205    }
206
207    /** @inheritDoc */
208    public function addImage( LinkTarget $name, $timestamp = null, $sha1 = null ): void {
209        # Fragments are stripped when collecting.
210        $link = $name->removeFragmentTarget();
211        $this->collect(
212            self::LINKTYPE_MEDIA,
213            $this->linkToString( $link ),
214            '',
215            self::MERGE_STRATEGY_WRITE_ONCE
216        );
217    }
218
219    /** @inheritDoc */
220    public function addLanguageLink( LinkTarget $lt ): void {
221        # Fragments are *not* stripped from language links.
222        # Language links are deduplicated by the interwiki prefix
223
224        # Note that, unlike some other types of collected metadata,
225        # language links are 'first wins' and the subsequent entries
226        # for the same language are ignored.
227        if ( $this->get( self::LINKTYPE_LANGUAGE, $lt->getInterwiki(), self::MERGE_STRATEGY_WRITE_ONCE ) !== null ) {
228            return;
229        }
230
231        $this->collect(
232            self::LINKTYPE_LANGUAGE,
233            $lt->getInterwiki(),
234            $this->linkToString( $lt ),
235            self::MERGE_STRATEGY_WRITE_ONCE
236        );
237    }
238
239    /**
240     * Add a dependency on the given template.
241     * @param LinkTarget $link
242     * @param int $page_id
243     * @param int $rev_id
244     */
245    public function addTemplate( LinkTarget $link, int $page_id, int $rev_id ): void {
246        # Fragments are stripped when collecting.
247        $link = $link->removeFragmentTarget();
248        // XXX should store the page_id and rev_id
249        $this->collect(
250            self::LINKTYPE_TEMPLATE,
251            $this->linkToString( $link ),
252            '',
253            self::MERGE_STRATEGY_WRITE_ONCE
254        );
255    }
256
257    /**
258     * @see ParserOutput::getLinkList()
259     * @param string $linkType A link type, which should be a constant from
260     *  this class
261     * @return list<array{link:LinkTarget,pageid?:int,revid?:int,sort?:string,time?:string|false,sha1?:string|false}>
262     */
263    public function getLinkList( string $linkType ): array {
264        $result = [];
265        switch ( $linkType ) {
266            case self::LINKTYPE_CATEGORY:
267                foreach ( $this->get( $linkType ) as $link => $sort ) {
268                    $result[] = [
269                        'link' => $this->stringToLink( (string)$link ),
270                        'sort' => $sort,
271                    ];
272                }
273                break;
274            case self::LINKTYPE_LANGUAGE:
275                foreach ( $this->get( $linkType ) as $lang => $link ) {
276                    $result[] = [
277                        'link' => $this->stringToLink( $link ),
278                    ];
279                }
280                break;
281            case self::LINKTYPE_INTERWIKI:
282            case self::LINKTYPE_LOCAL:
283            case self::LINKTYPE_MEDIA:
284            case self::LINKTYPE_SPECIAL:
285            case self::LINKTYPE_TEMPLATE:
286                foreach ( $this->get( $linkType ) as $link => $_ignore ) {
287                    $result[] = [
288                        'link' => $this->stringToLink( (string)$link ),
289                    ];
290                }
291                break;
292            default:
293                throw new UnreachableException( "Bad link type: $linkType" );
294        }
295        return $result;
296    }
297
298    /**
299     * Unified internal implementation of metadata collection.
300     * @param string $which Internal string identifying the type of metadata.
301     * @param string $key Key for storage (or '' if this is not relevant)
302     * @param mixed $value Value to store
303     * @param string|MergeStrategy $strategy "union" or "write-once"
304     */
305    private function collect(
306        string $which, string $key, $value,
307        string|MergeStrategy $strategy = MergeStrategy::UNION
308    ): void {
309        if ( $strategy instanceof MergeStrategy ) {
310            $strategy = $strategy->value;
311        }
312        if ( !array_key_exists( $which, $this->storage ) ) {
313            $this->storage[$which] = [];
314        }
315        if ( !array_key_exists( $key, $this->storage[$which] ) ) {
316            $this->storage[$which][$key] = [ self::MERGE_STRATEGY_KEY => $strategy ];
317            if ( $strategy === self::MERGE_STRATEGY_WRITE_ONCE ||
318                 $strategy === MergeStrategy::SUM->value ) {
319                $this->storage[$which][$key]['value'] = $value;
320                return;
321            }
322        }
323        if ( $this->storage[$which][$key][self::MERGE_STRATEGY_KEY] !== $strategy ) {
324            $this->logger->log(
325                LogLevel::WARNING,
326                "Conflicting strategies for $which $key"
327            );
328            // Destructive update for compatibility; this is deprecated!
329            $this->setOutputFlag( 'prevent-selective-update' );
330            unset( $this->storage[$which][$key] );
331            $this->collect( $which, $key, $value, $strategy );
332            return;
333        }
334        if ( $strategy === self::MERGE_STRATEGY_WRITE_ONCE ) {
335            if ( ( $this->storage[$which][$key]['value'] ?? null ) === $value ) {
336                return; // already exists with the desired value
337            }
338            // Destructive update for compatibility; this is discouraged
339            // because it disables selective update.
340            $this->setOutputFlag( 'prevent-selective-update' );
341            unset( $this->storage[$which][$key] );
342            $this->collect( $which, $key, $value, $strategy );
343            return;
344        } elseif ( $strategy === MergeStrategy::UNION->value ) {
345            if ( !( is_string( $value ) || is_int( $value ) ) ) {
346                throw new \InvalidArgumentException( "Bad value type for $key: " . get_debug_type( $value ) );
347            }
348            $this->storage[$which][$key][$value] = true;
349            return;
350        } elseif ( $strategy === MergeStrategy::SUM->value ) {
351            if ( !is_int( $value ) ) {
352                throw new \InvalidArgumentException( "Bad value type for $key: " . get_debug_type( $value ) );
353            }
354            $this->storage[$which][$key]['value'] += $value;
355            return;
356        } else {
357            throw new \InvalidArgumentException( "Unknown strategy: $strategy" );
358        }
359    }
360
361    /**
362     * Retrieve values from the collector.
363     * @param string $which Internal string identifying the type of metadata.
364     * @param string|null $key Key for storage (or '' if this is not relevant)
365     * @param string|MergeStrategy $defaultStrategy Determines whether to return an empty
366     *  array or null for a missing $key
367     * @return mixed
368     */
369    private function get(
370        string $which,
371        ?string $key = null,
372        string|MergeStrategy $defaultStrategy = MergeStrategy::UNION
373    ) {
374        if ( $defaultStrategy instanceof MergeStrategy ) {
375            $defaultStrategy = $defaultStrategy->value;
376        }
377        if ( $key !== null ) {
378            $result = ( $this->storage[$which] ?? [] )[$key] ?? [];
379            $strategy = $result[self::MERGE_STRATEGY_KEY] ?? $defaultStrategy;
380            unset( $result[self::MERGE_STRATEGY_KEY] );
381            if ( $strategy === self::MERGE_STRATEGY_WRITE_ONCE ) {
382                return $result['value'] ?? null;
383            } elseif ( $strategy === MergeStrategy::SUM->value ) {
384                return $result['value'] ?? 0;
385            } else {
386                return array_keys( $result );
387            }
388        }
389        $result = [];
390        foreach ( ( $this->storage[$which] ?? [] ) as $key => $_ignore ) {
391            $result[$key] = $this->get( $which, (string)$key );
392        }
393        return $result;
394    }
395
396    // @internal introspection methods
397
398    /** @return string[] */
399    public function getModules(): array {
400        return $this->get( 'outputstrings', CMCSS::MODULE );
401    }
402
403    /** @return string[] */
404    public function getModuleStyles(): array {
405        return $this->get( 'outputstrings', CMCSS::MODULE_STYLE );
406    }
407
408    /** @return string[] */
409    public function getJsConfigVars(): array {
410        // This is somewhat unusual, in that we expose the 'set' represenation
411        // as $key => true, instead of just returning array_keys().
412        $result = $this->storage['jsconfigvars'] ?? [];
413        foreach ( $result as $key => &$value ) {
414            $strategy = $value[self::MERGE_STRATEGY_KEY] ?? null;
415            unset( $value[self::MERGE_STRATEGY_KEY] );
416            if ( $strategy === self::MERGE_STRATEGY_WRITE_ONCE ||
417                 $strategy === MergeStrategy::SUM->value ) {
418                $value = array_keys( $value )[0];
419            }
420        }
421        return $result;
422    }
423
424    /** @return list<string> */
425    public function getCategoryNames(): array {
426        return array_map(
427            static fn ( $item ) => $item['link']->getDBkey(),
428            $this->getLinkList( self::LINKTYPE_CATEGORY )
429        );
430    }
431
432    /**
433     * @param string $name Category name
434     * @return ?string Sort key
435     */
436    public function getCategorySortKey( string $name ): ?string {
437        $tv = TitleValue::tryNew(
438            14, // NS_CATEGORY
439            $name
440        );
441        return $this->get(
442            self::LINKTYPE_CATEGORY,
443            $this->linkToString( $tv ),
444            self::MERGE_STRATEGY_WRITE_ONCE
445        );
446    }
447
448    /**
449     * @param string $name
450     * @return null|int|float|string
451     */
452    public function getPageProperty( string $name ) {
453        return $this->get( 'properties', $name, self::MERGE_STRATEGY_WRITE_ONCE );
454    }
455
456    /**
457     * Return the collected extension data under the given key.
458     * @param string $key
459     * @return mixed|null
460     */
461    public function getExtensionData( string $key ) {
462        return $this->get( 'extensiondata', $key, self::MERGE_STRATEGY_WRITE_ONCE );
463    }
464
465    /**
466     * Return the active output flags.
467     * @return string[]
468     */
469    public function getOutputFlags() {
470        $result = [];
471        foreach ( $this->get( 'outputflags', null ) as $key => $value ) {
472            if ( $value ) {
473                $result[] = $key;
474            }
475        }
476        return $result;
477    }
478
479    /**
480     * Return the collected TOC data, or null if no TOC data was collected.
481     * @return ?TOCData
482     */
483    public function getTOCData(): ?TOCData {
484        return $this->get( 'tocdata', '', self::MERGE_STRATEGY_WRITE_ONCE );
485    }
486
487    /**
488     * Set the content for an indicator.
489     * @param string $name
490     * @param string $content
491     */
492    public function setIndicator( $name, $content ): void {
493        $this->collect( 'indicators', $name, $content, self::MERGE_STRATEGY_WRITE_ONCE );
494    }
495
496    /**
497     * Return a "name" => "content-id" mapping of recorded indicators
498     * @return array
499     */
500    public function getIndicators(): array {
501        return $this->get( 'indicators' );
502    }
503
504    // helper functions for recording LinkTarget objects
505
506    /**
507     * Convert a LinkTarget to a string for storing in the collected metadata.
508     * @param LinkTarget $lt
509     * @return string
510     */
511    private function linkToString( LinkTarget $lt ): string {
512        return implode( '#', [
513            (string)$lt->getNamespace(),
514            $lt->getDBkey(),
515            $lt->getInterwiki(),
516            $lt->getFragment(),
517        ] );
518    }
519
520    /**
521     * Convert a string back into a LinkTarget for retrieval from the
522     * collected metadata.
523     * @param string $s
524     * @return LinkTarget
525     */
526    private function stringToLink( string $s ): LinkTarget {
527        [ $namespace, $dbkey, $interwiki, $fragment ] = explode( '#', $s, 4 );
528        return TitleValue::tryNew( (int)$namespace, $dbkey, $fragment, $interwiki );
529    }
530}