Completed
Push — master ( 47e7a3...c6464d )
by
unknown
25s
created
src/ConstraintCheck/Helper/SparqlHelper.php 1 patch
Spacing   +232 added lines, -236 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare( strict_types = 1 );
3
+declare(strict_types=1);
4 4
 
5 5
 namespace WikibaseQuality\ConstraintReport\ConstraintCheck\Helper;
6 6
 
@@ -166,143 +166,143 @@  discard block
 block discarded – undo
166 166
 		$this->defaultUserAgent = $defaultUserAgent;
167 167
 		$this->requestFactory = $requestFactory;
168 168
 		$this->entityPrefixes = [];
169
-		foreach ( $rdfVocabulary->entityNamespaceNames as $namespaceName ) {
170
-			$this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI( $namespaceName );
169
+		foreach ($rdfVocabulary->entityNamespaceNames as $namespaceName) {
170
+			$this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI($namespaceName);
171 171
 		}
172 172
 
173
-		$this->primaryEndpoint = $config->get( 'WBQualityConstraintsSparqlEndpoint' );
174
-		$this->additionalEndpoints = $config->get( 'WBQualityConstraintsAdditionalSparqlEndpoints' ) ?: [];
175
-		$this->maxQueryTimeMillis = $config->get( 'WBQualityConstraintsSparqlMaxMillis' );
176
-		$this->subclassOfId = new NumericPropertyId( $config->get( 'WBQualityConstraintsSubclassOfId' ) );
177
-		$this->cacheMapSize = $config->get( 'WBQualityConstraintsFormatCacheMapSize' );
173
+		$this->primaryEndpoint = $config->get('WBQualityConstraintsSparqlEndpoint');
174
+		$this->additionalEndpoints = $config->get('WBQualityConstraintsAdditionalSparqlEndpoints') ?: [];
175
+		$this->maxQueryTimeMillis = $config->get('WBQualityConstraintsSparqlMaxMillis');
176
+		$this->subclassOfId = new NumericPropertyId($config->get('WBQualityConstraintsSubclassOfId'));
177
+		$this->cacheMapSize = $config->get('WBQualityConstraintsFormatCacheMapSize');
178 178
 		$this->timeoutExceptionClasses = $config->get(
179 179
 			'WBQualityConstraintsSparqlTimeoutExceptionClasses'
180 180
 		);
181 181
 		$this->sparqlHasWikibaseSupport = $config->get(
182 182
 			'WBQualityConstraintsSparqlHasWikibaseSupport'
183 183
 		);
184
-		$this->sparqlThrottlingFallbackDuration = (int)$config->get(
184
+		$this->sparqlThrottlingFallbackDuration = (int) $config->get(
185 185
 			'WBQualityConstraintsSparqlThrottlingFallbackDuration'
186 186
 		);
187 187
 
188
-		$this->prefixes = $this->getQueryPrefixes( $rdfVocabulary );
188
+		$this->prefixes = $this->getQueryPrefixes($rdfVocabulary);
189 189
 
190 190
 		$this->rdfVocabularyWithoutNormalization = clone $rdfVocabulary;
191 191
 		// @phan-suppress-next-line PhanTypeMismatchProperty
192 192
 		$this->rdfVocabularyWithoutNormalization->normalizedPropertyValueNamespace = array_fill_keys(
193
-			array_keys( $rdfVocabulary->normalizedPropertyValueNamespace ),
193
+			array_keys($rdfVocabulary->normalizedPropertyValueNamespace),
194 194
 			null
195 195
 		);
196 196
 	}
197 197
 
198
-	private function getQueryPrefixes( RdfVocabulary $rdfVocabulary ): string {
198
+	private function getQueryPrefixes(RdfVocabulary $rdfVocabulary): string {
199 199
 		// TODO: it would probably be smarter that RdfVocabulary exposed these prefixes somehow
200 200
 		$prefixes = '';
201
-		foreach ( $rdfVocabulary->entityNamespaceNames as $sourceName => $namespaceName ) {
201
+		foreach ($rdfVocabulary->entityNamespaceNames as $sourceName => $namespaceName) {
202 202
 			$prefixes .= <<<END
203
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
203
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
204 204
 END;
205 205
 		}
206 206
 
207
-		foreach ( $rdfVocabulary->statementNamespaceNames as $sourceName => $sourceNamespaces ) {
207
+		foreach ($rdfVocabulary->statementNamespaceNames as $sourceName => $sourceNamespaces) {
208 208
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NS_VALUE];
209 209
 			$prefixes .= <<<END
210
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
210
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
211 211
 END;
212 212
 		}
213 213
 
214
-		foreach ( $rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces ) {
214
+		foreach ($rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces) {
215 215
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_DIRECT_CLAIM];
216 216
 			$prefixes .= <<<END
217
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
217
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
218 218
 END;
219 219
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM];
220 220
 			$prefixes .= <<<END
221
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
221
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
222 222
 END;
223 223
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM_STATEMENT];
224 224
 			$prefixes .= <<<END
225
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
225
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
226 226
 END;
227 227
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM_VALUE];
228 228
 			$prefixes .= <<<END
229
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
229
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
230 230
 END;
231 231
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER];
232 232
 			$prefixes .= <<<END
233
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
233
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
234 234
 END;
235 235
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER_VALUE];
236 236
 			$prefixes .= <<<END
237
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
237
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
238 238
 END;
239 239
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE];
240 240
 			$prefixes .= <<<END
241
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
241
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
242 242
 END;
243 243
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE_VALUE];
244 244
 			$prefixes .= <<<END
245
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
245
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
246 246
 END;
247 247
 		}
248 248
 		$namespaceName = RdfVocabulary::NS_ONTOLOGY;
249 249
 		$prefixes .= <<<END
250
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
250
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
251 251
 END;
252 252
 		return $prefixes;
253 253
 	}
254 254
 
255 255
 	/** Return a SPARQL term like `wd:Q123` for the given ID. */
256
-	private function wd( EntityId $id ): string {
257
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
256
+	private function wd(EntityId $id): string {
257
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
258 258
 		$prefix = $this->rdfVocabulary->entityNamespaceNames[$repository];
259 259
 		return "$prefix:{$id->getSerialization()}";
260 260
 	}
261 261
 
262 262
 	/** Return a SPARQL term like `wdt:P123` for the given ID. */
263
-	private function wdt( PropertyId $id ): string {
264
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
263
+	private function wdt(PropertyId $id): string {
264
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
265 265
 		$prefix = $this->rdfVocabulary->propertyNamespaceNames[$repository][RdfVocabulary::NSP_DIRECT_CLAIM];
266 266
 		return "$prefix:{$id->getSerialization()}";
267 267
 	}
268 268
 
269 269
 	/** Return a SPARQL term like `p:P123` for the given ID. */
270
-	private function p( PropertyId $id ): string {
271
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
270
+	private function p(PropertyId $id): string {
271
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
272 272
 		$prefix = $this->rdfVocabulary->propertyNamespaceNames[$repository][RdfVocabulary::NSP_CLAIM];
273 273
 		return "$prefix:{$id->getSerialization()}";
274 274
 	}
275 275
 
276 276
 	/** Return a SPARQL term like `pq:P123` for the given ID. */
277
-	private function pq( PropertyId $id ): string {
278
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
277
+	private function pq(PropertyId $id): string {
278
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
279 279
 		$prefix = $this->rdfVocabulary->propertyNamespaceNames[$repository][RdfVocabulary::NSP_QUALIFIER];
280 280
 		return "$prefix:{$id->getSerialization()}";
281 281
 	}
282 282
 
283 283
 	/** Return a SPARQL term like `wdno:P123` for the given ID. */
284
-	private function wdno( PropertyId $id ): string {
285
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
284
+	private function wdno(PropertyId $id): string {
285
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
286 286
 		$prefix = $this->rdfVocabulary->propertyNamespaceNames[$repository][RdfVocabulary::NSP_NOVALUE];
287 287
 		return "$prefix:{$id->getSerialization()}";
288 288
 	}
289 289
 
290 290
 	/** Return a SPARQL term like `prov:NAME` for the given name. */
291
-	private function prov( string $name ): string {
291
+	private function prov(string $name): string {
292 292
 		$prefix = RdfVocabulary::NS_PROV;
293 293
 		return "$prefix:$name";
294 294
 	}
295 295
 
296 296
 	/** Return a SPARQL term like `wikibase:NAME` for the given name. */
297
-	private function wikibase( string $name ): string {
297
+	private function wikibase(string $name): string {
298 298
 		$prefix = RdfVocabulary::NS_ONTOLOGY;
299 299
 		return "$prefix:$name";
300 300
 	}
301 301
 
302 302
 	/** Return a SPARQL snippet like `MINUS { ?var wikibase:rank wikibase:DeprecatedRank. }`. */
303
-	private function minusDeprecatedRank( string $varName ): string {
303
+	private function minusDeprecatedRank(string $varName): string {
304 304
 		$deprecatedRank = RdfVocabulary::RANK_MAP[Statement::RANK_DEPRECATED];
305
-		return "MINUS { $varName {$this->wikibase( 'rank' )} {$this->wikibase( $deprecatedRank )}. }";
305
+		return "MINUS { $varName {$this->wikibase('rank')} {$this->wikibase($deprecatedRank)}. }";
306 306
 	}
307 307
 
308 308
 	/**
@@ -312,43 +312,42 @@  discard block
 block discarded – undo
312 312
 	 * @return CachedBool
313 313
 	 * @throws SparqlHelperException if the query times out or some other error occurs
314 314
 	 */
315
-	public function hasType( EntityId $id, array $classes ): CachedBool {
315
+	public function hasType(EntityId $id, array $classes): CachedBool {
316 316
 		// TODO hint:gearing is a workaround for T168973 and can hopefully be removed eventually
317 317
 		$gearingHint = $this->sparqlHasWikibaseSupport ?
318
-			' hint:Prior hint:gearing "forward".' :
319
-			'';
318
+			' hint:Prior hint:gearing "forward".' : '';
320 319
 
321 320
 		$metadatas = [];
322 321
 
323
-		foreach ( array_chunk( $classes, 20 ) as $classesChunk ) {
324
-			$classesValues = implode( ' ', array_map(
325
-				function ( string $class ) {
326
-					return $this->wd( new ItemId( $class ) );
322
+		foreach (array_chunk($classes, 20) as $classesChunk) {
323
+			$classesValues = implode(' ', array_map(
324
+				function(string $class) {
325
+					return $this->wd(new ItemId($class));
327 326
 				},
328 327
 				$classesChunk
329
-			) );
328
+			));
330 329
 
331 330
 			$query = <<<EOF
332 331
 ASK {
333
-  BIND({$this->wd( $id )} AS ?item)
332
+  BIND({$this->wd($id)} AS ?item)
334 333
   VALUES ?class { $classesValues }
335
-  ?item {$this->wdt( $this->subclassOfId )}* ?class.$gearingHint
334
+  ?item {$this->wdt($this->subclassOfId)}* ?class.$gearingHint
336 335
 }
337 336
 EOF;
338 337
 
339
-			$result = $this->runQuery( $query, $this->primaryEndpoint );
338
+			$result = $this->runQuery($query, $this->primaryEndpoint);
340 339
 			$metadatas[] = $result->getMetadata();
341
-			if ( $result->getArray()['boolean'] ) {
340
+			if ($result->getArray()['boolean']) {
342 341
 				return new CachedBool(
343 342
 					true,
344
-					Metadata::merge( $metadatas )
343
+					Metadata::merge($metadatas)
345 344
 				);
346 345
 			}
347 346
 		}
348 347
 
349 348
 		return new CachedBool(
350 349
 			false,
351
-			Metadata::merge( $metadatas )
350
+			Metadata::merge($metadatas)
352 351
 		);
353 352
 	}
354 353
 
@@ -366,12 +365,12 @@  discard block
 block discarded – undo
366 365
 		array $separators
367 366
 	): CachedEntityIds {
368 367
 		$mainSnak = $statement->getMainSnak();
369
-		if ( !( $mainSnak instanceof PropertyValueSnak ) ) {
370
-			return new CachedEntityIds( [], Metadata::blank() );
368
+		if (!($mainSnak instanceof PropertyValueSnak)) {
369
+			return new CachedEntityIds([], Metadata::blank());
371 370
 		}
372 371
 
373 372
 		$propertyId = $statement->getPropertyId();
374
-		$pPredicateAndObject = "{$this->p( $propertyId )} ?otherStatement."; // p:P123 ?otherStatement.
373
+		$pPredicateAndObject = "{$this->p($propertyId)} ?otherStatement."; // p:P123 ?otherStatement.
375 374
 		$otherStatementPredicateAndObject = $this->getSnakPredicateAndObject(
376 375
 			$entityId,
377 376
 			$mainSnak,
@@ -380,57 +379,57 @@  discard block
 block discarded – undo
380 379
 
381 380
 		$isSeparator = [];
382 381
 		$unusedSeparators = [];
383
-		foreach ( $separators as $separator ) {
382
+		foreach ($separators as $separator) {
384 383
 			$isSeparator[$separator->getSerialization()] = true;
385 384
 			$unusedSeparators[$separator->getSerialization()] = $separator;
386 385
 		}
387 386
 		$separatorFilters = '';
388
-		foreach ( $statement->getQualifiers() as $qualifier ) {
387
+		foreach ($statement->getQualifiers() as $qualifier) {
389 388
 			$qualPropertyId = $qualifier->getPropertyId();
390
-			if ( !( $isSeparator[$qualPropertyId->getSerialization()] ?? false ) ) {
389
+			if (!($isSeparator[$qualPropertyId->getSerialization()] ?? false)) {
391 390
 				continue;
392 391
 			}
393
-			unset( $unusedSeparators[$qualPropertyId->getSerialization()] );
392
+			unset($unusedSeparators[$qualPropertyId->getSerialization()]);
394 393
 			// only look for other statements with the same qualifier
395
-			if ( $qualifier instanceof PropertyValueSnak ) {
394
+			if ($qualifier instanceof PropertyValueSnak) {
396 395
 				$sepPredicateAndObject = $this->getSnakPredicateAndObject(
397 396
 					$entityId,
398 397
 					$qualifier,
399 398
 					RdfVocabulary::NSP_QUALIFIER
400 399
 				);
401 400
 				$separatorFilters .= "  ?otherStatement $sepPredicateAndObject\n";
402
-			} elseif ( $qualifier instanceof PropertyNoValueSnak ) {
403
-				$sepPredicateAndObject = "a {$this->wdno( $qualPropertyId )}."; // a wdno:P123.
401
+			} elseif ($qualifier instanceof PropertyNoValueSnak) {
402
+				$sepPredicateAndObject = "a {$this->wdno($qualPropertyId)}."; // a wdno:P123.
404 403
 				$separatorFilters .= "  ?otherStatement $sepPredicateAndObject\n";
405 404
 			} else {
406 405
 				// "some value" / "unknown value" is always different from everything else,
407 406
 				// therefore the whole statement has no duplicates and we can return immediately
408
-				return new CachedEntityIds( [], Metadata::blank() );
407
+				return new CachedEntityIds([], Metadata::blank());
409 408
 			}
410 409
 		}
411
-		foreach ( $unusedSeparators as $unusedSeparator ) {
410
+		foreach ($unusedSeparators as $unusedSeparator) {
412 411
 			// exclude other statements which have a separator that this one lacks
413
-			$separatorFilters .= "  MINUS { ?otherStatement {$this->pq( $unusedSeparator )} []. }\n";
414
-			$separatorFilters .= "  MINUS { ?otherStatement a {$this->wdno( $unusedSeparator )}. }\n";
412
+			$separatorFilters .= "  MINUS { ?otherStatement {$this->pq($unusedSeparator)} []. }\n";
413
+			$separatorFilters .= "  MINUS { ?otherStatement a {$this->wdno($unusedSeparator)}. }\n";
415 414
 		}
416 415
 
417 416
 		$query = <<<SPARQL
418 417
 SELECT DISTINCT ?otherEntity WHERE {
419 418
   ?otherEntity $pPredicateAndObject
420 419
   ?otherStatement $otherStatementPredicateAndObject
421
-  {$this->minusDeprecatedRank( '?otherStatement' )}
422
-  FILTER(?otherEntity != {$this->wd( $entityId )})
420
+  {$this->minusDeprecatedRank('?otherStatement')}
421
+  FILTER(?otherEntity != {$this->wd($entityId)})
423 422
 $separatorFilters
424 423
 }
425 424
 LIMIT 10
426 425
 SPARQL;
427 426
 
428
-		$results = [ $this->runQuery( $query, $this->primaryEndpoint ) ];
429
-		foreach ( $this->additionalEndpoints as $endpoint ) {
430
-			$results[] = $this->runQuery( $query, $endpoint );
427
+		$results = [$this->runQuery($query, $this->primaryEndpoint)];
428
+		foreach ($this->additionalEndpoints as $endpoint) {
429
+			$results[] = $this->runQuery($query, $endpoint);
431 430
 		}
432 431
 
433
-		return $this->getOtherEntities( $results );
432
+		return $this->getOtherEntities($results);
434 433
 	}
435 434
 
436 435
 	/**
@@ -449,40 +448,38 @@  discard block
 block discarded – undo
449 448
 		bool $ignoreDeprecatedStatements
450 449
 	): CachedEntityIds {
451 450
 		$propertyId = $snak->getPropertyId();
452
-		$pPredicateAndObject = "{$this->p( $propertyId )} ?otherStatement."; // p:P123 ?otherStatement.
451
+		$pPredicateAndObject = "{$this->p($propertyId)} ?otherStatement."; // p:P123 ?otherStatement.
453 452
 
454 453
 		$otherSubject = $type === Context::TYPE_QUALIFIER ?
455
-			'?otherStatement' :
456
-			"?otherStatement {$this->prov( 'wasDerivedFrom' )} ?reference.\n  ?reference";
454
+			'?otherStatement' : "?otherStatement {$this->prov('wasDerivedFrom')} ?reference.\n  ?reference";
457 455
 		$otherPredicateAndObject = $this->getSnakPredicateAndObject(
458 456
 			$entityId,
459 457
 			$snak,
460 458
 			$type === Context::TYPE_QUALIFIER ?
461
-				RdfVocabulary::NSP_QUALIFIER :
462
-				RdfVocabulary::NSP_REFERENCE
459
+				RdfVocabulary::NSP_QUALIFIER : RdfVocabulary::NSP_REFERENCE
463 460
 		);
464 461
 
465 462
 		$deprecatedFilter = '';
466
-		if ( $ignoreDeprecatedStatements ) {
467
-			$deprecatedFilter = '  ' . $this->minusDeprecatedRank( '?otherStatement' );
463
+		if ($ignoreDeprecatedStatements) {
464
+			$deprecatedFilter = '  '.$this->minusDeprecatedRank('?otherStatement');
468 465
 		}
469 466
 
470 467
 		$query = <<<SPARQL
471 468
 SELECT DISTINCT ?otherEntity WHERE {
472 469
   ?otherEntity $pPredicateAndObject
473 470
   $otherSubject $otherPredicateAndObject
474
-  FILTER(?otherEntity != {$this->wd( $entityId )})
471
+  FILTER(?otherEntity != {$this->wd($entityId)})
475 472
 $deprecatedFilter
476 473
 }
477 474
 LIMIT 10
478 475
 SPARQL;
479 476
 
480
-		$results = [ $this->runQuery( $query, $this->primaryEndpoint ) ];
481
-		foreach ( $this->additionalEndpoints as $endpoint ) {
482
-			$results[] = $this->runQuery( $query, $endpoint );
477
+		$results = [$this->runQuery($query, $this->primaryEndpoint)];
478
+		foreach ($this->additionalEndpoints as $endpoint) {
479
+			$results[] = $this->runQuery($query, $endpoint);
483 480
 		}
484 481
 
485
-		return $this->getOtherEntities( $results );
482
+		return $this->getOtherEntities($results);
486 483
 	}
487 484
 
488 485
 	/**
@@ -513,13 +510,13 @@  discard block
 block discarded – undo
513 510
 		$writer->start();
514 511
 		$writer->drain();
515 512
 		$placeholder1 = 'wbqc';
516
-		$placeholder2 = 'x' . wfRandomString( 32 );
517
-		$writer->about( $placeholder1, $placeholder2 );
513
+		$placeholder2 = 'x'.wfRandomString(32);
514
+		$writer->about($placeholder1, $placeholder2);
518 515
 
519 516
 		$propertyId = $snak->getPropertyId();
520 517
 		$pid = $propertyId->getSerialization();
521
-		$propertyRepository = $this->rdfVocabulary->getEntityRepositoryName( $propertyId );
522
-		$entityRepository = $this->rdfVocabulary->getEntityRepositoryName( $entityId );
518
+		$propertyRepository = $this->rdfVocabulary->getEntityRepositoryName($propertyId);
519
+		$entityRepository = $this->rdfVocabulary->getEntityRepositoryName($entityId);
523 520
 		$propertyNamespace = $this->rdfVocabulary->propertyNamespaceNames[$propertyRepository][$namespace];
524 521
 		$value = $snak->getDataValue();
525 522
 		if (
@@ -550,21 +547,21 @@  discard block
 block discarded – undo
550 547
 				$writer,
551 548
 				$propertyNamespace,
552 549
 				$pid,
553
-				$this->propertyDataTypeLookup->getDataTypeIdForProperty( $propertyId ),
550
+				$this->propertyDataTypeLookup->getDataTypeIdForProperty($propertyId),
554 551
 				$this->rdfVocabulary->statementNamespaceNames[$entityRepository][RdfVocabulary::NS_VALUE], // should be unused
555 552
 				$snak
556 553
 			);
557 554
 		}
558 555
 
559 556
 		$triple = $writer->drain(); // wbqc:xRANDOM ps:PID "value". or similar
560
-		return trim( str_replace( "$placeholder1:$placeholder2", '', $triple ) );
557
+		return trim(str_replace("$placeholder1:$placeholder2", '', $triple));
561 558
 	}
562 559
 
563 560
 	/**
564 561
 	 * Return SPARQL code for a string literal with $text as content.
565 562
 	 */
566
-	private function stringLiteral( string $text ): string {
567
-		return '"' . strtr( $text, [ '"' => '\\"', '\\' => '\\\\' ] ) . '"';
563
+	private function stringLiteral(string $text): string {
564
+		return '"'.strtr($text, ['"' => '\\"', '\\' => '\\\\']).'"';
568 565
 	}
569 566
 
570 567
 	/**
@@ -574,26 +571,26 @@  discard block
 block discarded – undo
574 571
 	 *
575 572
 	 * @return CachedEntityIds
576 573
 	 */
577
-	private function getOtherEntities( array $results ): CachedEntityIds {
574
+	private function getOtherEntities(array $results): CachedEntityIds {
578 575
 		$allResultBindings = [];
579 576
 		$metadatas = [];
580 577
 
581
-		foreach ( $results as $result ) {
578
+		foreach ($results as $result) {
582 579
 			$metadatas[] = $result->getMetadata();
583
-			$allResultBindings = array_merge( $allResultBindings, $result->getArray()['results']['bindings'] );
580
+			$allResultBindings = array_merge($allResultBindings, $result->getArray()['results']['bindings']);
584 581
 		}
585 582
 
586 583
 		$entityIds = array_map(
587
-			function ( $resultBindings ) {
584
+			function($resultBindings) {
588 585
 				$entityIRI = $resultBindings['otherEntity']['value'];
589
-				foreach ( $this->entityPrefixes as $entityPrefix ) {
590
-					$entityPrefixLength = strlen( $entityPrefix );
591
-					if ( substr( $entityIRI, 0, $entityPrefixLength ) === $entityPrefix ) {
586
+				foreach ($this->entityPrefixes as $entityPrefix) {
587
+					$entityPrefixLength = strlen($entityPrefix);
588
+					if (substr($entityIRI, 0, $entityPrefixLength) === $entityPrefix) {
592 589
 						try {
593 590
 							return $this->entityIdParser->parse(
594
-								substr( $entityIRI, $entityPrefixLength )
591
+								substr($entityIRI, $entityPrefixLength)
595 592
 							);
596
-						} catch ( EntityIdParsingException ) {
593
+						} catch (EntityIdParsingException) {
597 594
 							// fall through
598 595
 						}
599 596
 					}
@@ -607,8 +604,8 @@  discard block
 block discarded – undo
607 604
 		);
608 605
 
609 606
 		return new CachedEntityIds(
610
-			array_values( array_filter( array_unique( $entityIds ) ) ),
611
-			Metadata::merge( $metadatas )
607
+			array_values(array_filter(array_unique($entityIds))),
608
+			Metadata::merge($metadatas)
612 609
 		);
613 610
 	}
614 611
 
@@ -616,63 +613,63 @@  discard block
 block discarded – undo
616 613
 	 * @throws SparqlHelperException if the query times out or some other error occurs
617 614
 	 * @throws ConstraintParameterException if the $regex is invalid
618 615
 	 */
619
-	public function matchesRegularExpression( string $text, string $regex ): bool {
616
+	public function matchesRegularExpression(string $text, string $regex): bool {
620 617
 		// caching wrapper around matchesRegularExpressionWithSparql
621 618
 
622
-		$textHash = hash( 'sha256', $text );
619
+		$textHash = hash('sha256', $text);
623 620
 		$cacheKey = $this->cache->makeKey(
624 621
 			'WikibaseQualityConstraints', // extension
625 622
 			'regex', // action
626 623
 			'WDQS-Java', // regex flavor
627
-			hash( 'sha256', $regex )
624
+			hash('sha256', $regex)
628 625
 		);
629 626
 
630 627
 		$baseRegexCacheKey = 'wikibase.quality.constraints.regex.cache';
631
-		$metric = $this->statsFactory->getCounter( 'regex_cache_total' );
628
+		$metric = $this->statsFactory->getCounter('regex_cache_total');
632 629
 
633 630
 		$cacheMapArray = $this->cache->getWithSetCallback(
634 631
 			$cacheKey,
635 632
 			WANObjectCache::TTL_DAY,
636
-			function ( $cacheMapArray ) use ( $text, $regex, $textHash, $metric, $baseRegexCacheKey ) {
633
+			function($cacheMapArray) use ($text, $regex, $textHash, $metric, $baseRegexCacheKey) {
637 634
 				// Initialize the cache map if not set
638
-				if ( $cacheMapArray === false ) {
635
+				if ($cacheMapArray === false) {
639 636
 					$metric
640
-						->setLabel( 'operation', 'refresh' )
641
-						->setLabel( 'status', 'init' )
642
-						->copyToStatsdAt( [
637
+						->setLabel('operation', 'refresh')
638
+						->setLabel('status', 'init')
639
+						->copyToStatsdAt([
643 640
 							"$baseRegexCacheKey.refresh.init",
644
-						] )->increment();
641
+						])->increment();
645 642
 
646 643
 					return [];
647 644
 				}
648 645
 
649
-				$cacheMap = MapCacheLRU::newFromArray( $cacheMapArray, $this->cacheMapSize );
650
-				if ( $cacheMap->has( $textHash ) ) {
646
+				$cacheMap = MapCacheLRU::newFromArray($cacheMapArray, $this->cacheMapSize);
647
+				if ($cacheMap->has($textHash)) {
651 648
 					$metric
652
-						->setLabel( 'operation', 'refresh' )
653
-						->setLabel( 'status', 'hit' )
654
-						->copyToStatsdAt( [
649
+						->setLabel('operation', 'refresh')
650
+						->setLabel('status', 'hit')
651
+						->copyToStatsdAt([
655 652
 							"$baseRegexCacheKey.refresh",
656 653
 							"$baseRegexCacheKey.refresh.hit",
657
-						] )
654
+						])
658 655
 						->increment();
659 656
 
660
-					$cacheMap->get( $textHash ); // ping cache
657
+					$cacheMap->get($textHash); // ping cache
661 658
 				} else {
662 659
 					$metric
663
-						->setLabel( 'operation', 'refresh' )
664
-						->setLabel( 'status', 'miss' )
665
-						->copyToStatsdAt( [
660
+						->setLabel('operation', 'refresh')
661
+						->setLabel('status', 'miss')
662
+						->copyToStatsdAt([
666 663
 							"$baseRegexCacheKey.refresh",
667 664
 							"$baseRegexCacheKey.refresh.miss",
668
-						] )
665
+						])
669 666
 						->increment();
670 667
 
671 668
 					try {
672
-						$matches = $this->matchesRegularExpressionWithSparql( $text, $regex );
673
-					} catch ( ConstraintParameterException $e ) {
674
-						$matches = $this->serializeConstraintParameterException( $e );
675
-					} catch ( SparqlHelperException ) {
669
+						$matches = $this->matchesRegularExpressionWithSparql($text, $regex);
670
+					} catch (ConstraintParameterException $e) {
671
+						$matches = $this->serializeConstraintParameterException($e);
672
+					} catch (SparqlHelperException) {
676 673
 						// don’t cache this
677 674
 						return $cacheMap->toArray();
678 675
 					}
@@ -696,54 +693,54 @@  discard block
 block discarded – undo
696 693
 			]
697 694
 		);
698 695
 
699
-		if ( isset( $cacheMapArray[$textHash] ) ) {
696
+		if (isset($cacheMapArray[$textHash])) {
700 697
 			$metric
701
-				->setLabel( 'operation', 'none' )
702
-				->setLabel( 'status', 'hit' )
703
-				->copyToStatsdAt( [
698
+				->setLabel('operation', 'none')
699
+				->setLabel('status', 'hit')
700
+				->copyToStatsdAt([
704 701
 					"$baseRegexCacheKey.hit",
705
-				] )
702
+				])
706 703
 				->increment();
707 704
 
708 705
 			$matches = $cacheMapArray[$textHash];
709
-			if ( is_bool( $matches ) ) {
706
+			if (is_bool($matches)) {
710 707
 				return $matches;
711
-			} elseif ( is_array( $matches ) &&
712
-				$matches['type'] == ConstraintParameterException::class ) {
713
-				throw $this->deserializeConstraintParameterException( $matches );
708
+			} elseif (is_array($matches) &&
709
+				$matches['type'] == ConstraintParameterException::class) {
710
+				throw $this->deserializeConstraintParameterException($matches);
714 711
 			} else {
715 712
 				throw new UnexpectedValueException(
716
-					'Value of unknown type in object cache (' .
717
-					'cache key: ' . $cacheKey . ', ' .
718
-					'cache map key: ' . $textHash . ', ' .
719
-					'value type: ' . get_debug_type( $matches ) . ')'
713
+					'Value of unknown type in object cache ('.
714
+					'cache key: '.$cacheKey.', '.
715
+					'cache map key: '.$textHash.', '.
716
+					'value type: '.get_debug_type($matches).')'
720 717
 				);
721 718
 			}
722 719
 		} else {
723 720
 			$metric
724
-				->setLabel( 'operation', 'none' )
725
-				->setLabel( 'status', 'miss' )
726
-				->copyToStatsdAt( [
721
+				->setLabel('operation', 'none')
722
+				->setLabel('status', 'miss')
723
+				->copyToStatsdAt([
727 724
 					"$baseRegexCacheKey.miss",
728
-				] )
725
+				])
729 726
 				->increment();
730 727
 
731
-			return $this->matchesRegularExpressionWithSparql( $text, $regex );
728
+			return $this->matchesRegularExpressionWithSparql($text, $regex);
732 729
 		}
733 730
 	}
734 731
 
735
-	private function serializeConstraintParameterException( ConstraintParameterException $cpe ): array {
732
+	private function serializeConstraintParameterException(ConstraintParameterException $cpe): array {
736 733
 		return [
737 734
 			'type' => ConstraintParameterException::class,
738
-			'violationMessage' => $this->violationMessageSerializer->serialize( $cpe->getViolationMessage() ),
735
+			'violationMessage' => $this->violationMessageSerializer->serialize($cpe->getViolationMessage()),
739 736
 		];
740 737
 	}
741 738
 
742
-	private function deserializeConstraintParameterException( array $serialization ): ConstraintParameterException {
739
+	private function deserializeConstraintParameterException(array $serialization): ConstraintParameterException {
743 740
 		$message = $this->violationMessageDeserializer->deserialize(
744 741
 			$serialization['violationMessage']
745 742
 		);
746
-		return new ConstraintParameterException( $message );
743
+		return new ConstraintParameterException($message);
747 744
 	}
748 745
 
749 746
 	/**
@@ -753,25 +750,25 @@  discard block
 block discarded – undo
753 750
 	 * @throws SparqlHelperException if the query times out or some other error occurs
754 751
 	 * @throws ConstraintParameterException if the $regex is invalid
755 752
 	 */
756
-	public function matchesRegularExpressionWithSparql( string $text, string $regex ): bool {
757
-		$textStringLiteral = $this->stringLiteral( $text );
758
-		$regexStringLiteral = $this->stringLiteral( '^(?:' . $regex . ')$' );
753
+	public function matchesRegularExpressionWithSparql(string $text, string $regex): bool {
754
+		$textStringLiteral = $this->stringLiteral($text);
755
+		$regexStringLiteral = $this->stringLiteral('^(?:'.$regex.')$');
759 756
 
760 757
 		$query = <<<EOF
761 758
 SELECT (REGEX($textStringLiteral, $regexStringLiteral) AS ?matches) {}
762 759
 EOF;
763 760
 
764
-		$result = $this->runQuery( $query, $this->primaryEndpoint, false );
761
+		$result = $this->runQuery($query, $this->primaryEndpoint, false);
765 762
 
766 763
 		$vars = $result->getArray()['results']['bindings'][0];
767
-		if ( array_key_exists( 'matches', $vars ) ) {
764
+		if (array_key_exists('matches', $vars)) {
768 765
 			// true or false ⇒ regex okay, text matches or not
769 766
 			return $vars['matches']['value'] === 'true';
770 767
 		} else {
771 768
 			// empty result: regex broken
772 769
 			throw new ConstraintParameterException(
773
-				( new ViolationMessage( 'wbqc-violation-message-parameter-regex' ) )
774
-					->withInlineCode( $regex, Role::CONSTRAINT_PARAMETER_VALUE )
770
+				(new ViolationMessage('wbqc-violation-message-parameter-regex'))
771
+					->withInlineCode($regex, Role::CONSTRAINT_PARAMETER_VALUE)
775 772
 			);
776 773
 		}
777 774
 	}
@@ -779,14 +776,14 @@  discard block
 block discarded – undo
779 776
 	/**
780 777
 	 * Check whether the text content of an error response indicates a query timeout.
781 778
 	 */
782
-	public function isTimeout( string $responseContent ): bool {
783
-		$timeoutRegex = implode( '|', array_map(
784
-			static function ( $fqn ) {
785
-				return preg_quote( $fqn, '/' );
779
+	public function isTimeout(string $responseContent): bool {
780
+		$timeoutRegex = implode('|', array_map(
781
+			static function($fqn) {
782
+				return preg_quote($fqn, '/');
786 783
 			},
787 784
 			$this->timeoutExceptionClasses
788
-		) );
789
-		return (bool)preg_match( '/' . $timeoutRegex . '/', $responseContent );
785
+		));
786
+		return (bool) preg_match('/'.$timeoutRegex.'/', $responseContent);
790 787
 	}
791 788
 
792 789
 	/**
@@ -798,17 +795,17 @@  discard block
 block discarded – undo
798 795
 	 * @return int|bool the max-age (in seconds)
799 796
 	 * or a plain boolean if no max-age can be determined
800 797
 	 */
801
-	public function getCacheMaxAge( array $responseHeaders ) {
798
+	public function getCacheMaxAge(array $responseHeaders) {
802 799
 		if (
803
-			array_key_exists( 'x-cache-status', $responseHeaders ) &&
804
-			preg_match( '/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0] )
800
+			array_key_exists('x-cache-status', $responseHeaders) &&
801
+			preg_match('/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0])
805 802
 		) {
806 803
 			$maxage = [];
807 804
 			if (
808
-				array_key_exists( 'cache-control', $responseHeaders ) &&
809
-				preg_match( '/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage )
805
+				array_key_exists('cache-control', $responseHeaders) &&
806
+				preg_match('/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage)
810 807
 			) {
811
-				return intval( $maxage[1] );
808
+				return intval($maxage[1]);
812 809
 			} else {
813 810
 				return true;
814 811
 			}
@@ -829,34 +826,34 @@  discard block
 block discarded – undo
829 826
 	 * or SparlHelper::EMPTY_RETRY_AFTER if there is an empty Retry-After
830 827
 	 * or SparlHelper::INVALID_RETRY_AFTER if there is something wrong with the format
831 828
 	 */
832
-	public function getThrottling( MWHttpRequest $request ) {
833
-		$retryAfterValue = $request->getResponseHeader( 'Retry-After' );
834
-		if ( $retryAfterValue === null ) {
829
+	public function getThrottling(MWHttpRequest $request) {
830
+		$retryAfterValue = $request->getResponseHeader('Retry-After');
831
+		if ($retryAfterValue === null) {
835 832
 			return self::NO_RETRY_AFTER;
836 833
 		}
837 834
 
838
-		$trimmedRetryAfterValue = trim( $retryAfterValue );
839
-		if ( $trimmedRetryAfterValue === '' ) {
835
+		$trimmedRetryAfterValue = trim($retryAfterValue);
836
+		if ($trimmedRetryAfterValue === '') {
840 837
 			return self::EMPTY_RETRY_AFTER;
841 838
 		}
842 839
 
843
-		if ( is_numeric( $trimmedRetryAfterValue ) ) {
844
-			$delaySeconds = (int)$trimmedRetryAfterValue;
845
-			if ( $delaySeconds >= 0 ) {
846
-				return $this->getTimestampInFuture( new DateInterval( 'PT' . $delaySeconds . 'S' ) );
840
+		if (is_numeric($trimmedRetryAfterValue)) {
841
+			$delaySeconds = (int) $trimmedRetryAfterValue;
842
+			if ($delaySeconds >= 0) {
843
+				return $this->getTimestampInFuture(new DateInterval('PT'.$delaySeconds.'S'));
847 844
 			}
848 845
 		} else {
849
-			$return = strtotime( $trimmedRetryAfterValue );
850
-			if ( $return !== false ) {
851
-				return new ConvertibleTimestamp( $return );
846
+			$return = strtotime($trimmedRetryAfterValue);
847
+			if ($return !== false) {
848
+				return new ConvertibleTimestamp($return);
852 849
 			}
853 850
 		}
854 851
 		return self::INVALID_RETRY_AFTER;
855 852
 	}
856 853
 
857
-	private function getTimestampInFuture( DateInterval $delta ): ConvertibleTimestamp {
854
+	private function getTimestampInFuture(DateInterval $delta): ConvertibleTimestamp {
858 855
 		$now = new ConvertibleTimestamp();
859
-		return new ConvertibleTimestamp( $now->timestamp->add( $delta ) );
856
+		return new ConvertibleTimestamp($now->timestamp->add($delta));
860 857
 	}
861 858
 
862 859
 	/**
@@ -871,110 +868,109 @@  discard block
 block discarded – undo
871 868
 	 *
872 869
 	 * @throws SparqlHelperException if the query times out or some other error occurs
873 870
 	 */
874
-	protected function runQuery( string $query, string $endpoint, bool $needsPrefixes = true ): CachedQueryResults {
871
+	protected function runQuery(string $query, string $endpoint, bool $needsPrefixes = true): CachedQueryResults {
875 872
 		$baseSPARQLKey = 'wikibase.quality.constraints.sparql';
876 873
 
877
-		if ( $this->throttlingLock->isLocked( self::EXPIRY_LOCK_ID ) ) {
874
+		if ($this->throttlingLock->isLocked(self::EXPIRY_LOCK_ID)) {
878 875
 			$this->statsFactory
879
-				->getCounter( 'sparql_throttling_total' )
880
-				->copyToStatsdAt( "$baseSPARQLKey.throttling" )
876
+				->getCounter('sparql_throttling_total')
877
+				->copyToStatsdAt("$baseSPARQLKey.throttling")
881 878
 				->increment();
882 879
 
883 880
 			throw new TooManySparqlRequestsException();
884 881
 		}
885 882
 
886
-		if ( $this->sparqlHasWikibaseSupport ) {
883
+		if ($this->sparqlHasWikibaseSupport) {
887 884
 			$needsPrefixes = false;
888 885
 		}
889 886
 
890
-		if ( $needsPrefixes ) {
891
-			$query = $this->prefixes . $query;
887
+		if ($needsPrefixes) {
888
+			$query = $this->prefixes.$query;
892 889
 		}
893
-		$query = "#wbqc\n" . $query;
890
+		$query = "#wbqc\n".$query;
894 891
 
895
-		$url = $endpoint . '?' . http_build_query(
892
+		$url = $endpoint.'?'.http_build_query(
896 893
 			[
897 894
 				'query' => $query,
898 895
 				'format' => 'json',
899 896
 				'maxQueryTimeMillis' => $this->maxQueryTimeMillis,
900 897
 			],
901
-			'', ini_get( 'arg_separator.output' ),
898
+			'', ini_get('arg_separator.output'),
902 899
 			// encode spaces with %20, not +
903 900
 			PHP_QUERY_RFC3986
904 901
 		);
905 902
 
906 903
 		$options = [
907 904
 			'method' => 'GET',
908
-			'timeout' => (int)round( ( $this->maxQueryTimeMillis + 1000 ) / 1000 ),
905
+			'timeout' => (int) round(($this->maxQueryTimeMillis + 1000) / 1000),
909 906
 			'connectTimeout' => 'default',
910 907
 			'userAgent' => $this->defaultUserAgent,
911 908
 		];
912
-		$request = $this->requestFactory->create( $url, $options, __METHOD__ );
909
+		$request = $this->requestFactory->create($url, $options, __METHOD__);
913 910
 
914 911
 		$timing = $this->statsFactory
915
-			->getTiming( 'sparql_runQuery_duration_seconds' )
916
-			->copyToStatsdAt( "$baseSPARQLKey.timing" );
912
+			->getTiming('sparql_runQuery_duration_seconds')
913
+			->copyToStatsdAt("$baseSPARQLKey.timing");
917 914
 
918 915
 		$timing->start();
919 916
 		$requestStatus = $request->execute();
920 917
 		$timing->stop();
921 918
 
922
-		$this->guardAgainstTooManyRequestsError( $request );
919
+		$this->guardAgainstTooManyRequestsError($request);
923 920
 
924
-		$maxAge = $this->getCacheMaxAge( $request->getResponseHeaders() );
925
-		if ( $maxAge ) {
926
-			$this->statsFactory->getCounter( 'sparql_cached_total' )
927
-				->copyToStatsdAt( "$baseSPARQLKey.cached" )
921
+		$maxAge = $this->getCacheMaxAge($request->getResponseHeaders());
922
+		if ($maxAge) {
923
+			$this->statsFactory->getCounter('sparql_cached_total')
924
+				->copyToStatsdAt("$baseSPARQLKey.cached")
928 925
 				->increment();
929 926
 		}
930 927
 
931 928
 		$sparqlErrorKey = "$baseSPARQLKey.error";
932
-		$metric = $this->statsFactory->getCounter( 'sparql_error_total' );
933
-		if ( $requestStatus->isOK() ) {
929
+		$metric = $this->statsFactory->getCounter('sparql_error_total');
930
+		if ($requestStatus->isOK()) {
934 931
 			$json = $request->getContent();
935
-			$jsonStatus = FormatJson::parse( $json, FormatJson::FORCE_ASSOC );
932
+			$jsonStatus = FormatJson::parse($json, FormatJson::FORCE_ASSOC);
936 933
 			'@phan-var \MediaWiki\Status\Status<array> $jsonStatus';
937
-			if ( $jsonStatus->isOK() ) {
934
+			if ($jsonStatus->isOK()) {
938 935
 				return new CachedQueryResults(
939 936
 					$jsonStatus->getValue(),
940 937
 					Metadata::ofCachingMetadata(
941 938
 						$maxAge ?
942
-							CachingMetadata::ofMaximumAgeInSeconds( $maxAge ) :
943
-							CachingMetadata::fresh()
939
+							CachingMetadata::ofMaximumAgeInSeconds($maxAge) : CachingMetadata::fresh()
944 940
 					)
945 941
 				);
946 942
 			} else {
947 943
 				$jsonErrorCode = $jsonStatus->getErrors()[0]['message'];
948 944
 				$metric
949
-					->setLabel( 'type', 'json' )
950
-					->setLabel( 'code', "$jsonErrorCode" )
951
-					->copyToStatsdAt( [
945
+					->setLabel('type', 'json')
946
+					->setLabel('code', "$jsonErrorCode")
947
+					->copyToStatsdAt([
952 948
 						"$sparqlErrorKey",
953 949
 						"$sparqlErrorKey.json.$jsonErrorCode",
954
-					] )
950
+					])
955 951
 					->increment();
956 952
 				// fall through to general error handling
957 953
 			}
958 954
 		} else {
959 955
 			$metric
960
-				->setLabel( 'type', 'http' )
961
-				->setLabel( 'code', "{$request->getStatus()}" )
962
-				->copyToStatsdAt( [
956
+				->setLabel('type', 'http')
957
+				->setLabel('code', "{$request->getStatus()}")
958
+				->copyToStatsdAt([
963 959
 					"$sparqlErrorKey",
964 960
 					"$sparqlErrorKey.http.{$request->getStatus()}",
965
-				] )
961
+				])
966 962
 				->increment();
967 963
 			// fall through to general error handling
968 964
 		}
969 965
 
970
-		if ( $this->isTimeout( $request->getContent() ) ) {
966
+		if ($this->isTimeout($request->getContent())) {
971 967
 			$metric
972
-				->setLabel( 'type', 'timeout' )
973
-				->setLabel( 'code', 'none' )
974
-				->copyToStatsdAt( [
968
+				->setLabel('type', 'timeout')
969
+				->setLabel('code', 'none')
970
+				->copyToStatsdAt([
975 971
 					"$sparqlErrorKey",
976 972
 					"$sparqlErrorKey.timeout",
977
-				] )
973
+				])
978 974
 				->increment();
979 975
 		}
980 976
 
@@ -987,33 +983,33 @@  discard block
 block discarded – undo
987 983
 	 * @param MWHttpRequest $request
988 984
 	 * @throws TooManySparqlRequestsException
989 985
 	 */
990
-	private function guardAgainstTooManyRequestsError( MWHttpRequest $request ): void {
991
-		if ( $request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS ) {
986
+	private function guardAgainstTooManyRequestsError(MWHttpRequest $request): void {
987
+		if ($request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS) {
992 988
 			return;
993 989
 		}
994 990
 
995 991
 		$fallbackBlockDuration = $this->sparqlThrottlingFallbackDuration;
996 992
 
997
-		if ( $fallbackBlockDuration < 0 ) {
998
-			throw new InvalidArgumentException( 'Fallback duration must be positive int but is: ' .
999
-				$fallbackBlockDuration );
993
+		if ($fallbackBlockDuration < 0) {
994
+			throw new InvalidArgumentException('Fallback duration must be positive int but is: '.
995
+				$fallbackBlockDuration);
1000 996
 		}
1001 997
 
1002 998
 		$throttlingKey = "wikibase.quality.constraints.sparql.throttling";
1003
-		$this->statsFactory->getCounter( 'sparql_throttling_total' )
1004
-			->copyToStatsdAt( $throttlingKey )
999
+		$this->statsFactory->getCounter('sparql_throttling_total')
1000
+			->copyToStatsdAt($throttlingKey)
1005 1001
 			->increment();
1006 1002
 
1007
-		$throttlingUntil = $this->getThrottling( $request );
1008
-		if ( !( $throttlingUntil instanceof ConvertibleTimestamp ) ) {
1009
-			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid( $request );
1003
+		$throttlingUntil = $this->getThrottling($request);
1004
+		if (!($throttlingUntil instanceof ConvertibleTimestamp)) {
1005
+			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid($request);
1010 1006
 			$this->throttlingLock->lock(
1011 1007
 				self::EXPIRY_LOCK_ID,
1012
-				$this->getTimestampInFuture( new DateInterval( 'PT' . $fallbackBlockDuration . 'S' ) )
1008
+				$this->getTimestampInFuture(new DateInterval('PT'.$fallbackBlockDuration.'S'))
1013 1009
 			);
1014 1010
 		} else {
1015
-			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent( $throttlingUntil, $request );
1016
-			$this->throttlingLock->lock( self::EXPIRY_LOCK_ID, $throttlingUntil );
1011
+			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent($throttlingUntil, $request);
1012
+			$this->throttlingLock->lock(self::EXPIRY_LOCK_ID, $throttlingUntil);
1017 1013
 		}
1018 1014
 		throw new TooManySparqlRequestsException();
1019 1015
 	}
Please login to merge, or discard this patch.
src/Api/CheckConstraintParameters.php 1 patch
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare( strict_types = 1 );
3
+declare(strict_types=1);
4 4
 
5 5
 namespace WikibaseQuality\ConstraintReport\Api;
6 6
 
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 			$delegatingConstraintChecker,
66 66
 			$violationMessageRendererFactory,
67 67
 			$statementGuidParser,
68
-			$statsFactory->withComponent( 'WikibaseQualityConstraints' )
68
+			$statsFactory->withComponent('WikibaseQualityConstraints')
69 69
 		);
70 70
 	}
71 71
 
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
 		StatementGuidParser $statementGuidParser,
80 80
 		StatsFactory $statsFactory
81 81
 	) {
82
-		parent::__construct( $main, $name );
82
+		parent::__construct($main, $name);
83 83
 
84
-		$this->apiErrorReporter = $apiHelperFactory->getErrorReporter( $this );
84
+		$this->apiErrorReporter = $apiHelperFactory->getErrorReporter($this);
85 85
 		$this->languageFallbackChainFactory = $languageFallbackChainFactory;
86 86
 		$this->delegatingConstraintChecker = $delegatingConstraintChecker;
87 87
 		$this->violationMessageRendererFactory = $violationMessageRendererFactory;
@@ -90,45 +90,45 @@  discard block
 block discarded – undo
90 90
 	}
91 91
 
92 92
 	public function execute() {
93
-		$this->statsFactory->getCounter( 'check_constraint_parameters_execute_total' )
93
+		$this->statsFactory->getCounter('check_constraint_parameters_execute_total')
94 94
 			->increment();
95 95
 
96 96
 		$params = $this->extractRequestParams();
97 97
 		$result = $this->getResult();
98 98
 
99
-		$propertyIds = $this->parsePropertyIds( $params[self::PARAM_PROPERTY_ID] );
100
-		$constraintIds = $this->parseConstraintIds( $params[self::PARAM_CONSTRAINT_ID] );
99
+		$propertyIds = $this->parsePropertyIds($params[self::PARAM_PROPERTY_ID]);
100
+		$constraintIds = $this->parseConstraintIds($params[self::PARAM_CONSTRAINT_ID]);
101 101
 
102
-		$this->checkPropertyIds( $propertyIds, $result );
103
-		$this->checkConstraintIds( $constraintIds, $result );
102
+		$this->checkPropertyIds($propertyIds, $result);
103
+		$this->checkConstraintIds($constraintIds, $result);
104 104
 
105
-		$result->addValue( null, 'success', 1 );
105
+		$result->addValue(null, 'success', 1);
106 106
 	}
107 107
 
108 108
 	/**
109 109
 	 * @param array|null $propertyIdSerializations
110 110
 	 * @return NumericPropertyId[]
111 111
 	 */
112
-	private function parsePropertyIds( ?array $propertyIdSerializations ): array {
113
-		if ( $propertyIdSerializations === null ) {
112
+	private function parsePropertyIds(?array $propertyIdSerializations): array {
113
+		if ($propertyIdSerializations === null) {
114 114
 			return [];
115
-		} elseif ( $propertyIdSerializations === [] ) {
115
+		} elseif ($propertyIdSerializations === []) {
116 116
 			$this->apiErrorReporter->dieError(
117
-				'If ' . self::PARAM_PROPERTY_ID . ' is specified, it must be nonempty.',
117
+				'If '.self::PARAM_PROPERTY_ID.' is specified, it must be nonempty.',
118 118
 				'no-data'
119 119
 			);
120 120
 		}
121 121
 
122 122
 		return array_map(
123
-			function ( $propertyIdSerialization ) {
123
+			function($propertyIdSerialization) {
124 124
 				try {
125
-					return new NumericPropertyId( $propertyIdSerialization );
126
-				} catch ( InvalidArgumentException ) {
125
+					return new NumericPropertyId($propertyIdSerialization);
126
+				} catch (InvalidArgumentException) {
127 127
 					$this->apiErrorReporter->dieError(
128 128
 						"Invalid id: $propertyIdSerialization",
129 129
 						'invalid-property-id',
130 130
 						0, // default argument
131
-						[ self::PARAM_PROPERTY_ID => $propertyIdSerialization ]
131
+						[self::PARAM_PROPERTY_ID => $propertyIdSerialization]
132 132
 					);
133 133
 				}
134 134
 			},
@@ -140,35 +140,35 @@  discard block
 block discarded – undo
140 140
 	 * @param array|null $constraintIds
141 141
 	 * @return string[]
142 142
 	 */
143
-	private function parseConstraintIds( ?array $constraintIds ): array {
144
-		if ( $constraintIds === null ) {
143
+	private function parseConstraintIds(?array $constraintIds): array {
144
+		if ($constraintIds === null) {
145 145
 			return [];
146
-		} elseif ( $constraintIds === [] ) {
146
+		} elseif ($constraintIds === []) {
147 147
 			$this->apiErrorReporter->dieError(
148
-				'If ' . self::PARAM_CONSTRAINT_ID . ' is specified, it must be nonempty.',
148
+				'If '.self::PARAM_CONSTRAINT_ID.' is specified, it must be nonempty.',
149 149
 				'no-data'
150 150
 			);
151 151
 		}
152 152
 
153 153
 		return array_map(
154
-			function ( $constraintId ) {
154
+			function($constraintId) {
155 155
 				try {
156
-					$propertyId = $this->statementGuidParser->parse( $constraintId )->getEntityId();
157
-					if ( !$propertyId instanceof NumericPropertyId ) {
156
+					$propertyId = $this->statementGuidParser->parse($constraintId)->getEntityId();
157
+					if (!$propertyId instanceof NumericPropertyId) {
158 158
 						$this->apiErrorReporter->dieError(
159 159
 							"Invalid property ID: {$propertyId->getSerialization()}",
160 160
 							'invalid-property-id',
161 161
 							0, // default argument
162
-							[ self::PARAM_CONSTRAINT_ID => $constraintId ]
162
+							[self::PARAM_CONSTRAINT_ID => $constraintId]
163 163
 						);
164 164
 					}
165 165
 					return $constraintId;
166
-				} catch ( StatementGuidParsingException ) {
166
+				} catch (StatementGuidParsingException) {
167 167
 					$this->apiErrorReporter->dieError(
168 168
 						"Invalid statement GUID: $constraintId",
169 169
 						'invalid-guid',
170 170
 						0, // default argument
171
-						[ self::PARAM_CONSTRAINT_ID => $constraintId ]
171
+						[self::PARAM_CONSTRAINT_ID => $constraintId]
172 172
 					);
173 173
 				}
174 174
 			},
@@ -180,12 +180,12 @@  discard block
 block discarded – undo
180 180
 	 * @param NumericPropertyId[] $propertyIds
181 181
 	 * @param ApiResult $result
182 182
 	 */
183
-	private function checkPropertyIds( array $propertyIds, ApiResult $result ): void {
184
-		foreach ( $propertyIds as $propertyId ) {
185
-			$result->addArrayType( $this->getResultPathForPropertyId( $propertyId ), 'assoc' );
183
+	private function checkPropertyIds(array $propertyIds, ApiResult $result): void {
184
+		foreach ($propertyIds as $propertyId) {
185
+			$result->addArrayType($this->getResultPathForPropertyId($propertyId), 'assoc');
186 186
 			$allConstraintExceptions = $this->delegatingConstraintChecker
187
-				->checkConstraintParametersOnPropertyId( $propertyId );
188
-			foreach ( $allConstraintExceptions as $constraintId => $constraintParameterExceptions ) {
187
+				->checkConstraintParametersOnPropertyId($propertyId);
188
+			foreach ($allConstraintExceptions as $constraintId => $constraintParameterExceptions) {
189 189
 				$this->addConstraintParameterExceptionsToResult(
190 190
 					$constraintId,
191 191
 					$constraintParameterExceptions,
@@ -199,15 +199,15 @@  discard block
 block discarded – undo
199 199
 	 * @param string[] $constraintIds
200 200
 	 * @param ApiResult $result
201 201
 	 */
202
-	private function checkConstraintIds( array $constraintIds, ApiResult $result ): void {
203
-		foreach ( $constraintIds as $constraintId ) {
204
-			if ( $result->getResultData( $this->getResultPathForConstraintId( $constraintId ) ) ) {
202
+	private function checkConstraintIds(array $constraintIds, ApiResult $result): void {
203
+		foreach ($constraintIds as $constraintId) {
204
+			if ($result->getResultData($this->getResultPathForConstraintId($constraintId))) {
205 205
 				// already checked as part of checkPropertyIds()
206 206
 				continue;
207 207
 			}
208 208
 			$constraintParameterExceptions = $this->delegatingConstraintChecker
209
-				->checkConstraintParametersOnConstraintId( $constraintId );
210
-			$this->addConstraintParameterExceptionsToResult( $constraintId, $constraintParameterExceptions, $result );
209
+				->checkConstraintParametersOnConstraintId($constraintId);
210
+			$this->addConstraintParameterExceptionsToResult($constraintId, $constraintParameterExceptions, $result);
211 211
 		}
212 212
 	}
213 213
 
@@ -215,18 +215,18 @@  discard block
 block discarded – undo
215 215
 	 * @param NumericPropertyId $propertyId
216 216
 	 * @return string[]
217 217
 	 */
218
-	private function getResultPathForPropertyId( NumericPropertyId $propertyId ): array {
219
-		return [ $this->getModuleName(), $propertyId->getSerialization() ];
218
+	private function getResultPathForPropertyId(NumericPropertyId $propertyId): array {
219
+		return [$this->getModuleName(), $propertyId->getSerialization()];
220 220
 	}
221 221
 
222 222
 	/**
223 223
 	 * @param string $constraintId
224 224
 	 * @return string[]
225 225
 	 */
226
-	private function getResultPathForConstraintId( string $constraintId ): array {
227
-		$propertyId = $this->statementGuidParser->parse( $constraintId )->getEntityId();
226
+	private function getResultPathForConstraintId(string $constraintId): array {
227
+		$propertyId = $this->statementGuidParser->parse($constraintId)->getEntityId();
228 228
 		'@phan-var NumericPropertyId $propertyId';
229
-		return array_merge( $this->getResultPathForPropertyId( $propertyId ), [ $constraintId ] );
229
+		return array_merge($this->getResultPathForPropertyId($propertyId), [$constraintId]);
230 230
 	}
231 231
 
232 232
 	/**
@@ -241,8 +241,8 @@  discard block
 block discarded – undo
241 241
 		?array $constraintParameterExceptions,
242 242
 		ApiResult $result
243 243
 	): void {
244
-		$path = $this->getResultPathForConstraintId( $constraintId );
245
-		if ( $constraintParameterExceptions === null ) {
244
+		$path = $this->getResultPathForConstraintId($constraintId);
245
+		if ($constraintParameterExceptions === null) {
246 246
 			$result->addValue(
247 247
 				$path,
248 248
 				self::KEY_STATUS,
@@ -259,11 +259,11 @@  discard block
 block discarded – undo
259 259
 			$violationMessageRenderer = $this->violationMessageRendererFactory
260 260
 				->getViolationMessageRenderer(
261 261
 					$language,
262
-					$this->languageFallbackChainFactory->newFromLanguage( $language ),
262
+					$this->languageFallbackChainFactory->newFromLanguage($language),
263 263
 					$this
264 264
 				);
265 265
 			$problems = [];
266
-			foreach ( $constraintParameterExceptions as $constraintParameterException ) {
266
+			foreach ($constraintParameterExceptions as $constraintParameterException) {
267 267
 				$problems[] = [
268 268
 					self::KEY_MESSAGE_HTML => $violationMessageRenderer->render(
269 269
 						$constraintParameterException->getViolationMessage() ),
@@ -302,8 +302,8 @@  discard block
 block discarded – undo
302 302
 		return [
303 303
 			'action=wbcheckconstraintparameters&propertyid=P247'
304 304
 				=> 'apihelp-wbcheckconstraintparameters-example-propertyid-1',
305
-			'action=wbcheckconstraintparameters&' .
306
-			'constraintid=P247$0fe1711e-4c0f-82ce-3af0-830b721d0fba|' .
305
+			'action=wbcheckconstraintparameters&'.
306
+			'constraintid=P247$0fe1711e-4c0f-82ce-3af0-830b721d0fba|'.
307 307
 			'P225$cdc71e4a-47a0-12c5-dfb3-3f6fc0b6613f'
308 308
 				=> 'apihelp-wbcheckconstraintparameters-example-constraintid-2',
309 309
 		];
Please login to merge, or discard this patch.