Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
79.49% covered (warning)
79.49%
62 / 78
77.78% covered (warning)
77.78%
7 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
WikibaseClientSiteLinksForItemHookHandler
79.49% covered (warning)
79.49%
62 / 78
77.78% covered (warning)
77.78%
7 / 9
31.83
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 onWikibaseClientSiteLinksForItem
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 addSiteLink
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getCommonsSiteLink
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
5
 getLinkedItemSitelink
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 getCommonsCategoryName
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 getCommonsSitelinkFromMainSnaks
52.38% covered (warning)
52.38%
11 / 21
0.00% covered (danger)
0.00%
0 / 1
14.91
 getItem
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getStringValueFromMainSnaks
45.45% covered (danger)
45.45%
5 / 11
0.00% covered (danger)
0.00%
0 / 1
6.60
1<?php
2
3declare( strict_types = 1 );
4
5namespace WikimediaBadges;
6
7use DataValues\StringValue;
8use MediaWiki\Config\Config;
9use OutOfBoundsException;
10use Wikibase\Client\Hooks\WikibaseClientSiteLinksForItemHook;
11use Wikibase\Client\Usage\UsageAccumulator;
12use Wikibase\DataModel\Entity\EntityIdValue;
13use Wikibase\DataModel\Entity\Item;
14use Wikibase\DataModel\Entity\ItemId;
15use Wikibase\DataModel\Entity\NumericPropertyId;
16use Wikibase\DataModel\Services\Lookup\EntityLookup;
17use Wikibase\DataModel\Services\Lookup\EntityLookupException;
18use Wikibase\DataModel\SiteLink;
19use Wikibase\DataModel\Snak\PropertyValueSnak;
20use Wikibase\DataModel\Snak\Snak;
21
22/**
23 * Handler for the WikibaseClientSiteLinksForItem hook that changes the link
24 * to Wikimedia Commons with the one to the commons category.
25 *
26 * @since 0.1
27 *
28 * @license GPL-2.0-or-later
29 * @author Marius Hoch < hoo@online.de >
30 */
31class WikibaseClientSiteLinksForItemHookHandler implements WikibaseClientSiteLinksForItemHook {
32
33    /** @var string|null */
34    private $topicsMainCategoryProperty;
35
36    /** @var string|null */
37    private $categoryRelatedToListProperty;
38
39    /**
40     * @var string|null
41     */
42    private $commonsCategoryPropertySetting;
43
44    public function __construct(
45        Config $config,
46        private readonly EntityLookup $entityLookup,
47    ) {
48        $this->topicsMainCategoryProperty = $config->get( 'WikimediaBadgesTopicsMainCategoryProperty' );
49        $this->categoryRelatedToListProperty = $config->get( 'WikimediaBadgesCategoryRelatedToListProperty' );
50        $this->commonsCategoryPropertySetting = $config->get( 'WikimediaBadgesCommonsCategoryProperty' );
51    }
52
53    /** @inheritDoc */
54    public function onWikibaseClientSiteLinksForItem(
55        Item $item,
56        array &$siteLinks,
57        UsageAccumulator $usageAccumulator
58    ): void {
59        $sitelink = $this->getCommonsSiteLink( $item );
60        if ( $sitelink !== null ) {
61            $this->addSiteLink( $sitelink, $siteLinks );
62        }
63    }
64
65    /**
66     * @param string $siteLink
67     * @param SiteLink[] &$siteLinks
68     */
69    private function addSiteLink( string $siteLink, array &$siteLinks ): void {
70        $siteLinks['commonswiki'] = new SiteLink( 'commonswiki', $siteLink );
71    }
72
73    private function getCommonsSiteLink( Item $item ): ?string {
74        try {
75            return $item->getSiteLink( 'commonswiki' )->getPageName();
76        } catch ( OutOfBoundsException ) {
77            // pass
78        }
79
80        $topicsMainCategorySitelink = $this->getLinkedItemSitelink(
81            $item,
82            $this->topicsMainCategoryProperty
83        );
84        if ( $topicsMainCategorySitelink !== null ) {
85            return $topicsMainCategorySitelink;
86        }
87
88        $categoryRelatedToListSitelink = $this->getLinkedItemSitelink(
89            $item,
90            $this->categoryRelatedToListProperty
91        );
92        if ( $categoryRelatedToListSitelink !== null ) {
93            return $categoryRelatedToListSitelink;
94        }
95
96        $categoryName = $this->getCommonsCategoryName( $item );
97        if ( $categoryName !== null ) {
98            return 'Category:' . $categoryName;
99        }
100
101        return null;
102    }
103
104    private function getLinkedItemSitelink( Item $item, ?string $propertyIdString ): ?string {
105        if ( $propertyIdString === null ) {
106            return null;
107        }
108
109        $propertyId = new NumericPropertyId( $propertyIdString );
110        $statements = $item->getStatements()->getByPropertyId( $propertyId );
111
112        $mainSnaks = $statements->getBestStatements()->getMainSnaks();
113
114        return $this->getCommonsSitelinkFromMainSnaks(
115            $mainSnaks,
116            $item->getId(),
117            $propertyId
118        );
119    }
120
121    private function getCommonsCategoryName( Item $item ): ?string {
122        if ( $this->commonsCategoryPropertySetting === null ) {
123            return null;
124        }
125
126        $propertyId = new NumericPropertyId( $this->commonsCategoryPropertySetting );
127        $statements = $item->getStatements()->getByPropertyId( $propertyId );
128
129        $mainSnaks = $statements->getBestStatements()->getMainSnaks();
130
131        return $this->getStringValueFromMainSnaks(
132            $mainSnaks,
133            $item->getId(),
134            $propertyId
135        );
136    }
137
138    private function getCommonsSitelinkFromMainSnaks(
139        array $mainSnaks,
140        ItemId $itemId,
141        NumericPropertyId $propertyId
142    ): ?string {
143        foreach ( $mainSnaks as $snak ) {
144            if ( !( $snak instanceof PropertyValueSnak ) ) {
145                continue;
146            }
147
148            $dataValue = $snak->getDataValue();
149            if ( !(
150                $dataValue instanceof EntityIdValue &&
151                $dataValue->getEntityId() instanceof ItemId
152            ) ) {
153                wfLogWarning(
154                    $itemId->getSerialization() . ' has a PropertyValueSnak with ' .
155                    $propertyId->getSerialization() . ' that has non-ItemId data.'
156                );
157
158                continue;
159            }
160            $itemId = $dataValue->getEntityId();
161            '@phan-var ItemId $itemId';
162
163            try {
164                $item = $this->getItem( $itemId );
165            } catch ( EntityLookupException ) {
166                continue;
167            }
168            if ( $item === null ) {
169                continue;
170            }
171
172            try {
173                return $item->getSiteLink( 'commonswiki' )->getPageName();
174            } catch ( OutOfBoundsException ) {
175                continue;
176            }
177        }
178
179        return null;
180    }
181
182    /** @throws EntityLookupException */
183    private function getItem( ItemId $itemId ): ?Item {
184        return $this->entityLookup->getEntity( $itemId );
185    }
186
187    /**
188     * @param Snak[] $mainSnaks
189     * @param ItemId $itemId
190     * @param NumericPropertyId $propertyId
191     *
192     * @return string|null
193     */
194    private function getStringValueFromMainSnaks(
195        array $mainSnaks,
196        ItemId $itemId,
197        NumericPropertyId $propertyId
198    ): ?string {
199        foreach ( $mainSnaks as $snak ) {
200            if ( !( $snak instanceof PropertyValueSnak ) ) {
201                continue;
202            }
203
204            if ( !( $snak->getDataValue() instanceof StringValue ) ) {
205                wfLogWarning(
206                    $itemId->getSerialization() . ' has a PropertyValueSnak with ' .
207                        $propertyId->getSerialization() . ' that has non-StringValue data.'
208                );
209
210                continue;
211            }
212
213            return $snak->getDataValue()->getValue();
214        }
215
216        return null;
217    }
218}