EntityTerms::execute()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 9.52
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace Wikibase\Repo\Api;
6
7
use ApiQuery;
8
use ApiQueryBase;
9
use ApiResult;
10
use InvalidArgumentException;
11
use Title;
12
use Wikibase\DataAccess\AliasTermBuffer;
13
use Wikibase\DataModel\Entity\EntityId;
14
use Wikibase\DataModel\Services\Term\TermBuffer;
15
use Wikibase\Lib\Store\EntityIdLookup;
16
use Wikibase\Lib\TermIndexEntry;
17
use Wikibase\Repo\WikibaseRepo;
18
19
/**
20
 * Provides wikibase terms (labels, descriptions, aliases) for entity pages.
21
 * For example, if data item Q61 has the label "Washington" and the description
22
 * "capital city of the US", calling entityterms with titles=Q61 would include
23
 * that label and description in the response.
24
 *
25
 * @note This closely mirrors the Client pageterms API, except for the factory method.
26
 *
27
 * @license GPL-2.0-or-later
28
 */
29
class EntityTerms extends ApiQueryBase {
30
31
	/**
32
	 * @todo Use LabelDescriptionLookup for labels/descriptions, so we can apply language fallback.
33
	 * @var TermBuffer|AliasTermBuffer
34
	 */
35
	private $termBuffer;
36
37
	/**
38
	 * @var EntityIdLookup
39
	 */
40
	private $idLookup;
41
42
	public function __construct(
43
		TermBuffer $termBuffer,
44
		EntityIdLookup $idLookup,
45
		ApiQuery $query,
46
		string $moduleName
47
	) {
48
		parent::__construct( $query, $moduleName, 'wbet' );
49
		$this->termBuffer = $termBuffer;
50
		$this->idLookup = $idLookup;
51
	}
52
53
	public static function factory( ApiQuery $apiQuery, string $moduleName ): self {
54
		$repo = WikibaseRepo::getDefaultInstance();
55
		$termBuffer = $repo->getTermBuffer();
56
		$entityIdLookup = $repo->getEntityContentFactory();
57
58
		return new self(
59
			$termBuffer,
60
			$entityIdLookup,
61
			$apiQuery,
62
			$moduleName
63
		);
64
	}
65
66
	public function execute(): void {
67
		$params = $this->extractRequestParams();
68
69
		# Only operate on existing pages
70
		$titles = $this->getPageSet()->getGoodTitles();
71
		if ( !count( $titles ) ) {
72
			# Nothing to do
73
			return;
74
		}
75
76
		// NOTE: continuation relies on $titles being sorted by page ID.
77
		ksort( $titles );
78
79
		$continue = $params['continue'];
80
		$termTypes = $params['terms'] ?? TermIndexEntry::$validTermTypes;
81
82
		$pagesToEntityIds = $this->getEntityIdsForTitles( $titles, $continue );
83
		$entityToPageMap = $this->getEntityToPageMap( $pagesToEntityIds );
84
85
		$terms = $this->getTermsOfEntities( $pagesToEntityIds, $termTypes, $this->getLanguage()->getCode() );
86
87
		$termGroups = $this->groupTermsByPageAndType( $entityToPageMap, $terms );
88
89
		$this->addTermsToResult( $pagesToEntityIds, $termGroups );
90
	}
91
92
	/**
93
	 * @param EntityId[] $entityIds
94
	 * @param string[] $termTypes
95
	 * @param string $languageCode
96
	 *
97
	 * @return TermIndexEntry[]
98
	 */
99
	private function getTermsOfEntities( array $entityIds, array $termTypes, string $languageCode ): array {
100
		$this->termBuffer->prefetchTerms( $entityIds, $termTypes, [ $languageCode ] );
0 ignored issues
show
Bug introduced by
The method prefetchTerms does only exist in Wikibase\DataModel\Services\Term\TermBuffer, but not in Wikibase\DataAccess\AliasTermBuffer.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
101
102
		$terms = [];
103
		foreach ( $entityIds as $entityId ) {
104
			foreach ( $termTypes as $termType ) {
105
				if ( $termType !== 'alias' ) {
106
					$termText = $this->termBuffer->getPrefetchedTerm( $entityId, $termType, $languageCode );
0 ignored issues
show
Bug introduced by
The method getPrefetchedTerm does only exist in Wikibase\DataModel\Services\Term\TermBuffer, but not in Wikibase\DataAccess\AliasTermBuffer.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
107
					if ( $termText !== false && $termText !== null ) {
108
						$terms[] = new TermIndexEntry( [
109
							TermIndexEntry::FIELD_ENTITY => $entityId,
110
							TermIndexEntry::FIELD_TYPE => $termType,
111
							TermIndexEntry::FIELD_LANGUAGE => $languageCode,
112
							TermIndexEntry::FIELD_TEXT => $termText,
113
						] );
114
					}
115
				} else {
116
					$termTexts = $this->termBuffer->getPrefetchedAliases( $entityId, $languageCode ) ?: [];
0 ignored issues
show
Bug introduced by
The method getPrefetchedAliases does only exist in Wikibase\DataAccess\AliasTermBuffer, but not in Wikibase\DataModel\Services\Term\TermBuffer.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
117
					foreach ( $termTexts as $termText ) {
118
						$terms[] = new TermIndexEntry( [
119
							TermIndexEntry::FIELD_ENTITY => $entityId,
120
							TermIndexEntry::FIELD_TYPE => $termType,
121
							TermIndexEntry::FIELD_LANGUAGE => $languageCode,
122
							TermIndexEntry::FIELD_TEXT => $termText,
123
						] );
124
					}
125
				}
126
127
			}
128
		}
129
130
		return $terms;
131
	}
132
133
	/**
134
	 * @param Title[] $titles
135
	 * @param int|null $continue
136
	 *
137
	 * @return array
138
	 */
139
	private function getEntityIdsForTitles( array $titles, $continue = 0 ): array {
140
		$entityIds = $this->idLookup->getEntityIds( $titles );
141
142
		// Re-sort, so the order of page IDs matches the order in which $titles
143
		// were given. This is essential for paging to work properly.
144
		// This also skips all page IDs up to $continue.
145
		$sortedEntityId = [];
146
		foreach ( $titles as $pid => $title ) {
147
			if ( $pid >= $continue && isset( $entityIds[$pid] ) ) {
148
				$sortedEntityId[$pid] = $entityIds[$pid];
149
			}
150
		}
151
152
		return $sortedEntityId;
153
	}
154
155
	/**
156
	 * @param EntityId[] $entityIds
157
	 *
158
	 * @return int[]
159
	 */
160
	private function getEntityToPageMap( array $entityIds ): array {
161
		$entityIdsStrings = array_map(
162
			function( EntityId $id ) {
163
				return $id->getSerialization();
164
			},
165
			$entityIds
166
		);
167
168
		return array_flip( $entityIdsStrings );
169
	}
170
171
	/**
172
	 * @param int[] $entityToPageMap
173
	 * @param TermIndexEntry[] $terms
174
	 *
175
	 * @return array[] An associative array, mapping pageId + entity type to a list of strings.
176
	 */
177
	private function groupTermsByPageAndType( array $entityToPageMap, array $terms ): array {
178
		$termsPerPage = [];
179
180
		foreach ( $terms as $term ) {
181
			// Since we construct $terms and $entityToPageMap from the same set of page IDs,
182
			// the entry $entityToPageMap[$key] should really always be set.
183
			$type = $term->getTermType();
184
			$key = $term->getEntityId()->getSerialization();
185
			$pageId = $entityToPageMap[$key];
186
			$text = $term->getText();
187
188
			if ( $text !== null ) {
189
				// For each page ID, record a list of terms for each term type.
190
				$termsPerPage[$pageId][$type][] = $text;
191
			} else {
192
				// $text should never be null, but let's be vigilant.
193
				wfWarn( __METHOD__ . ': Encountered null text in TermIndexEntry object!' );
194
			}
195
		}
196
197
		return $termsPerPage;
198
	}
199
200
	/**
201
	 * @param EntityId[] $pagesToEntityIds
202
	 * @param array[] $termGroups
203
	 */
204
	private function addTermsToResult( array $pagesToEntityIds, array $termGroups ): void {
205
		$result = $this->getResult();
206
207
		foreach ( $pagesToEntityIds as $currentPage => $entityId ) {
208
			if ( !isset( $termGroups[$currentPage] ) ) {
209
				// No entity for page, or no terms for entity.
210
				continue;
211
			}
212
213
			$group = $termGroups[$currentPage];
214
215
			if ( !$this->addTermsForPage( $result, $currentPage, $group ) ) {
216
				break;
217
			}
218
		}
219
	}
220
221
	/**
222
	 * Add page term to an ApiResult, adding a continue
223
	 * parameter if it doesn't fit.
224
	 *
225
	 * @param ApiResult $result
226
	 * @param int $pageId
227
	 * @param array[] $termsByType
228
	 *
229
	 * @throws InvalidArgumentException
230
	 * @return bool True if it fits in the result
231
	 */
232
	private function addTermsForPage( ApiResult $result, int $pageId, array $termsByType ): bool {
233
		ApiResult::setIndexedTagNameRecursive( $termsByType, 'term' );
234
235
		$fit = $result->addValue( [ 'query', 'pages', $pageId ], 'entityterms', $termsByType );
236
237
		if ( !$fit ) {
238
			$this->setContinueEnumParameter( 'continue', $pageId );
239
		}
240
241
		return $fit;
242
	}
243
244
	/**
245
	 * @see ApiQueryBase::getCacheMode
246
	 *
247
	 * @param array $params
248
	 * @return string
249
	 */
250
	public function getCacheMode( $params ): string {
251
		return 'public';
252
	}
253
254
	/**
255
	 * @inheritDoc
256
	 */
257
	protected function getAllowedParams(): array {
258
		return [
259
			'continue' => [
260
				self::PARAM_HELP_MSG => 'api-help-param-continue',
261
				self::PARAM_TYPE => 'integer',
262
			],
263
			'terms' => [
264
				self::PARAM_TYPE => TermIndexEntry::$validTermTypes,
265
				self::PARAM_DFLT => implode( '|',  TermIndexEntry::$validTermTypes ),
266
				self::PARAM_ISMULTI => true,
267
				self::PARAM_HELP_MSG => 'apihelp-query+entityterms-param-terms',
268
			],
269
		];
270
	}
271
272
	/**
273
	 * @inheritDoc
274
	 */
275
	protected function getExamplesMessages(): array {
276
		return [
277
			'action=query&prop=entityterms&titles=Q84'
278
				=> 'apihelp-query+entityterms-example-item',
279
		];
280
	}
281
282
}
283