Completed
Push — master ( 692202...e8870b )
by
unknown
05:01 queued 02:13
created
src/ConstraintCheck/Helper/SparqlHelper.php 1 patch
Spacing   +164 added lines, -166 removed lines patch added patch discarded remove patch
@@ -161,19 +161,19 @@  discard block
 block discarded – undo
161 161
 		$this->loggingHelper = $loggingHelper;
162 162
 		$this->defaultUserAgent = $defaultUserAgent;
163 163
 		$this->requestFactory = $requestFactory;
164
-		$this->entityPrefix = $rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_ENTITY );
164
+		$this->entityPrefix = $rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_ENTITY);
165 165
 		$this->prefixes = <<<EOT
166
-PREFIX wd: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_ENTITY )}>
167
-PREFIX wds: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_STATEMENT )}>
168
-PREFIX wdt: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_DIRECT_CLAIM )}>
169
-PREFIX wdv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_VALUE )}>
170
-PREFIX p: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_CLAIM )}>
171
-PREFIX ps: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_CLAIM_STATEMENT )}>
172
-PREFIX pq: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_QUALIFIER )}>
173
-PREFIX pqv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_QUALIFIER_VALUE )}>
174
-PREFIX pr: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_REFERENCE )}>
175
-PREFIX prv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_REFERENCE_VALUE )}>
176
-PREFIX wikibase: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_ONTOLOGY )}>
166
+PREFIX wd: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_ENTITY)}>
167
+PREFIX wds: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_STATEMENT)}>
168
+PREFIX wdt: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_DIRECT_CLAIM)}>
169
+PREFIX wdv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_VALUE)}>
170
+PREFIX p: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_CLAIM)}>
171
+PREFIX ps: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_CLAIM_STATEMENT)}>
172
+PREFIX pq: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_QUALIFIER)}>
173
+PREFIX pqv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_QUALIFIER_VALUE)}>
174
+PREFIX pr: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_REFERENCE)}>
175
+PREFIX prv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_REFERENCE_VALUE)}>
176
+PREFIX wikibase: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_ONTOLOGY)}>
177 177
 EOT;
178 178
 	}
179 179
 
@@ -185,21 +185,21 @@  discard block
 block discarded – undo
185 185
 	 * @return CachedBool
186 186
 	 * @throws SparqlHelperException if the query times out or some other error occurs
187 187
 	 */
188
-	public function hasType( $id, array $classes, $withInstance ) {
189
-		$instanceOfId = $this->config->get( 'WBQualityConstraintsInstanceOfId' );
190
-		$subclassOfId = $this->config->get( 'WBQualityConstraintsSubclassOfId' );
188
+	public function hasType($id, array $classes, $withInstance) {
189
+		$instanceOfId = $this->config->get('WBQualityConstraintsInstanceOfId');
190
+		$subclassOfId = $this->config->get('WBQualityConstraintsSubclassOfId');
191 191
 
192
-		$path = ( $withInstance ? "wdt:$instanceOfId/" : "" ) . "wdt:$subclassOfId*";
192
+		$path = ($withInstance ? "wdt:$instanceOfId/" : "")."wdt:$subclassOfId*";
193 193
 
194 194
 		$metadatas = [];
195 195
 
196
-		foreach ( array_chunk( $classes, 20 ) as $classesChunk ) {
197
-			$classesValues = implode( ' ', array_map(
198
-				function( $class ) {
199
-					return 'wd:' . $class;
196
+		foreach (array_chunk($classes, 20) as $classesChunk) {
197
+			$classesValues = implode(' ', array_map(
198
+				function($class) {
199
+					return 'wd:'.$class;
200 200
 				},
201 201
 				$classesChunk
202
-			) );
202
+			));
203 203
 
204 204
 			$query = <<<EOF
205 205
 ASK {
@@ -210,19 +210,19 @@  discard block
 block discarded – undo
210 210
 EOF;
211 211
 			// TODO hint:gearing is a workaround for T168973 and can hopefully be removed eventually
212 212
 
213
-			$result = $this->runQuery( $query );
213
+			$result = $this->runQuery($query);
214 214
 			$metadatas[] = $result->getMetadata();
215
-			if ( $result->getArray()['boolean'] ) {
215
+			if ($result->getArray()['boolean']) {
216 216
 				return new CachedBool(
217 217
 					true,
218
-					Metadata::merge( $metadatas )
218
+					Metadata::merge($metadatas)
219 219
 				);
220 220
 			}
221 221
 		}
222 222
 
223 223
 		return new CachedBool(
224 224
 			false,
225
-			Metadata::merge( $metadatas )
225
+			Metadata::merge($metadatas)
226 226
 		);
227 227
 	}
228 228
 
@@ -238,10 +238,10 @@  discard block
 block discarded – undo
238 238
 		$ignoreDeprecatedStatements
239 239
 	) {
240 240
 		$pid = $statement->getPropertyId()->serialize();
241
-		$guid = str_replace( '$', '-', $statement->getGuid() );
241
+		$guid = str_replace('$', '-', $statement->getGuid());
242 242
 
243 243
 		$deprecatedFilter = '';
244
-		if ( $ignoreDeprecatedStatements ) {
244
+		if ($ignoreDeprecatedStatements) {
245 245
 			$deprecatedFilter = 'MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. }';
246 246
 		}
247 247
 
@@ -260,9 +260,9 @@  discard block
 block discarded – undo
260 260
 LIMIT 10
261 261
 EOF;
262 262
 
263
-		$result = $this->runQuery( $query );
263
+		$result = $this->runQuery($query);
264 264
 
265
-		return $this->getOtherEntities( $result );
265
+		return $this->getOtherEntities($result);
266 266
 	}
267 267
 
268 268
 	/**
@@ -287,16 +287,15 @@  discard block
 block discarded – undo
287 287
 		$dataType = $this->propertyDataTypeLookup->getDataTypeIdForProperty(
288 288
 			$snak->getPropertyId()
289 289
 		);
290
-		list( $value, $isFullValue ) = $this->getRdfLiteral( $dataType, $dataValue );
291
-		if ( $isFullValue ) {
290
+		list($value, $isFullValue) = $this->getRdfLiteral($dataType, $dataValue);
291
+		if ($isFullValue) {
292 292
 			$prefix .= 'v';
293 293
 		}
294 294
 		$path = $type === Context::TYPE_QUALIFIER ?
295
-			"$prefix:$pid" :
296
-			"prov:wasDerivedFrom/$prefix:$pid";
295
+			"$prefix:$pid" : "prov:wasDerivedFrom/$prefix:$pid";
297 296
 
298 297
 		$deprecatedFilter = '';
299
-		if ( $ignoreDeprecatedStatements ) {
298
+		if ($ignoreDeprecatedStatements) {
300 299
 			$deprecatedFilter = <<< EOF
301 300
   MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. }
302 301
 EOF;
@@ -316,9 +315,9 @@  discard block
 block discarded – undo
316 315
 LIMIT 10
317 316
 EOF;
318 317
 
319
-		$result = $this->runQuery( $query );
318
+		$result = $this->runQuery($query);
320 319
 
321
-		return $this->getOtherEntities( $result );
320
+		return $this->getOtherEntities($result);
322 321
 	}
323 322
 
324 323
 	/**
@@ -328,8 +327,8 @@  discard block
 block discarded – undo
328 327
 	 *
329 328
 	 * @return string
330 329
 	 */
331
-	private function stringLiteral( $text ) {
332
-		return '"' . strtr( $text, [ '"' => '\\"', '\\' => '\\\\' ] ) . '"';
330
+	private function stringLiteral($text) {
331
+		return '"'.strtr($text, ['"' => '\\"', '\\' => '\\\\']).'"';
333 332
 	}
334 333
 
335 334
 	/**
@@ -339,17 +338,17 @@  discard block
 block discarded – undo
339 338
 	 *
340 339
 	 * @return CachedEntityIds
341 340
 	 */
342
-	private function getOtherEntities( CachedQueryResults $results ) {
343
-		return new CachedEntityIds( array_map(
344
-			function ( $resultBindings ) {
341
+	private function getOtherEntities(CachedQueryResults $results) {
342
+		return new CachedEntityIds(array_map(
343
+			function($resultBindings) {
345 344
 				$entityIRI = $resultBindings['otherEntity']['value'];
346
-				$entityPrefixLength = strlen( $this->entityPrefix );
347
-				if ( substr( $entityIRI, 0, $entityPrefixLength ) === $this->entityPrefix ) {
345
+				$entityPrefixLength = strlen($this->entityPrefix);
346
+				if (substr($entityIRI, 0, $entityPrefixLength) === $this->entityPrefix) {
348 347
 					try {
349 348
 						return $this->entityIdParser->parse(
350
-							substr( $entityIRI, $entityPrefixLength )
349
+							substr($entityIRI, $entityPrefixLength)
351 350
 						);
352
-					} catch ( EntityIdParsingException $e ) {
351
+					} catch (EntityIdParsingException $e) {
353 352
 						// fall through
354 353
 					}
355 354
 				}
@@ -357,7 +356,7 @@  discard block
 block discarded – undo
357 356
 				return null;
358 357
 			},
359 358
 			$results->getArray()['results']['bindings']
360
-		), $results->getMetadata() );
359
+		), $results->getMetadata());
361 360
 	}
362 361
 
363 362
 	// @codingStandardsIgnoreStart cyclomatic complexity of this function is too high
@@ -370,47 +369,47 @@  discard block
 block discarded – undo
370 369
 	 * @return array the literal or IRI as a string in SPARQL syntax,
371 370
 	 * and a boolean indicating whether it refers to a full value node or not
372 371
 	 */
373
-	private function getRdfLiteral( $dataType, DataValue $dataValue ) {
374
-		switch ( $dataType ) {
372
+	private function getRdfLiteral($dataType, DataValue $dataValue) {
373
+		switch ($dataType) {
375 374
 			case 'string':
376 375
 			case 'external-id':
377
-				return [ $this->stringLiteral( $dataValue->getValue() ), false ];
376
+				return [$this->stringLiteral($dataValue->getValue()), false];
378 377
 			case 'commonsMedia':
379
-				$url = $this->rdfVocabulary->getMediaFileURI( $dataValue->getValue() );
380
-				return [ '<' . $url . '>', false ];
378
+				$url = $this->rdfVocabulary->getMediaFileURI($dataValue->getValue());
379
+				return ['<'.$url.'>', false];
381 380
 			case 'geo-shape':
382
-				$url = $this->rdfVocabulary->getGeoShapeURI( $dataValue->getValue() );
383
-				return [ '<' . $url . '>', false ];
381
+				$url = $this->rdfVocabulary->getGeoShapeURI($dataValue->getValue());
382
+				return ['<'.$url.'>', false];
384 383
 			case 'tabular-data':
385
-				$url = $this->rdfVocabulary->getTabularDataURI( $dataValue->getValue() );
386
-				return [ '<' . $url . '>', false ];
384
+				$url = $this->rdfVocabulary->getTabularDataURI($dataValue->getValue());
385
+				return ['<'.$url.'>', false];
387 386
 			case 'url':
388 387
 				$url = $dataValue->getValue();
389
-				if ( !preg_match( '/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url ) ) {
388
+				if (!preg_match('/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url)) {
390 389
 					// not a valid URL for SPARQL (see SPARQL spec, production 139 IRIREF)
391 390
 					// such an URL should never reach us, so just throw
392
-					throw new InvalidArgumentException( 'invalid URL: ' . $url );
391
+					throw new InvalidArgumentException('invalid URL: '.$url);
393 392
 				}
394
-				return [ '<' . $url . '>', false ];
393
+				return ['<'.$url.'>', false];
395 394
 			case 'wikibase-item':
396 395
 			case 'wikibase-property':
397 396
 				/** @var EntityIdValue $dataValue */
398
-				return [ 'wd:' . $dataValue->getEntityId()->getSerialization(), false ];
397
+				return ['wd:'.$dataValue->getEntityId()->getSerialization(), false];
399 398
 			case 'monolingualtext':
400 399
 				/** @var MonolingualTextValue $dataValue */
401 400
 				$lang = $dataValue->getLanguageCode();
402
-				if ( !preg_match( '/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang ) ) {
401
+				if (!preg_match('/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang)) {
403 402
 					// not a valid language tag for SPARQL (see SPARQL spec, production 145 LANGTAG)
404 403
 					// such a language tag should never reach us, so just throw
405
-					throw new InvalidArgumentException( 'invalid language tag: ' . $lang );
404
+					throw new InvalidArgumentException('invalid language tag: '.$lang);
406 405
 				}
407
-				return [ $this->stringLiteral( $dataValue->getText() ) . '@' . $lang, false ];
406
+				return [$this->stringLiteral($dataValue->getText()).'@'.$lang, false];
408 407
 			case 'globe-coordinate':
409 408
 			case 'quantity':
410 409
 			case 'time':
411
-				return [ 'wdv:' . $dataValue->getHash(), true ];
410
+				return ['wdv:'.$dataValue->getHash(), true];
412 411
 			default:
413
-				throw new InvalidArgumentException( 'unknown data type: ' . $dataType );
412
+				throw new InvalidArgumentException('unknown data type: '.$dataType);
414 413
 		}
415 414
 	}
416 415
 	// @codingStandardsIgnoreEnd
@@ -423,44 +422,44 @@  discard block
 block discarded – undo
423 422
 	 * @throws SparqlHelperException if the query times out or some other error occurs
424 423
 	 * @throws ConstraintParameterException if the $regex is invalid
425 424
 	 */
426
-	public function matchesRegularExpression( $text, $regex ) {
425
+	public function matchesRegularExpression($text, $regex) {
427 426
 		// caching wrapper around matchesRegularExpressionWithSparql
428 427
 
429
-		$textHash = hash( 'sha256', $text );
428
+		$textHash = hash('sha256', $text);
430 429
 		$cacheKey = $this->cache->makeKey(
431 430
 			'WikibaseQualityConstraints', // extension
432 431
 			'regex', // action
433 432
 			'WDQS-Java', // regex flavor
434
-			hash( 'sha256', $regex )
433
+			hash('sha256', $regex)
435 434
 		);
436
-		$cacheMapSize = $this->config->get( 'WBQualityConstraintsFormatCacheMapSize' );
435
+		$cacheMapSize = $this->config->get('WBQualityConstraintsFormatCacheMapSize');
437 436
 
438 437
 		$cacheMapArray = $this->cache->getWithSetCallback(
439 438
 			$cacheKey,
440 439
 			WANObjectCache::TTL_DAY,
441
-			function( $cacheMapArray ) use ( $text, $regex, $textHash, $cacheMapSize ) {
440
+			function($cacheMapArray) use ($text, $regex, $textHash, $cacheMapSize) {
442 441
 				// Initialize the cache map if not set
443
-				if ( $cacheMapArray === false ) {
442
+				if ($cacheMapArray === false) {
444 443
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.init';
445
-					$this->dataFactory->increment( $key );
444
+					$this->dataFactory->increment($key);
446 445
 					return [];
447 446
 				}
448 447
 
449 448
 				$key = 'wikibase.quality.constraints.regex.cache.refresh';
450
-				$this->dataFactory->increment( $key );
451
-				$cacheMap = MapCacheLRU::newFromArray( $cacheMapArray, $cacheMapSize );
452
-				if ( $cacheMap->has( $textHash ) ) {
449
+				$this->dataFactory->increment($key);
450
+				$cacheMap = MapCacheLRU::newFromArray($cacheMapArray, $cacheMapSize);
451
+				if ($cacheMap->has($textHash)) {
453 452
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.hit';
454
-					$this->dataFactory->increment( $key );
455
-					$cacheMap->get( $textHash ); // ping cache
453
+					$this->dataFactory->increment($key);
454
+					$cacheMap->get($textHash); // ping cache
456 455
 				} else {
457 456
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.miss';
458
-					$this->dataFactory->increment( $key );
457
+					$this->dataFactory->increment($key);
459 458
 					try {
460
-						$matches = $this->matchesRegularExpressionWithSparql( $text, $regex );
461
-					} catch ( ConstraintParameterException $e ) {
462
-						$matches = $this->serializeConstraintParameterException( $e );
463
-					} catch ( SparqlHelperException $e ) {
459
+						$matches = $this->matchesRegularExpressionWithSparql($text, $regex);
460
+					} catch (ConstraintParameterException $e) {
461
+						$matches = $this->serializeConstraintParameterException($e);
462
+					} catch (SparqlHelperException $e) {
464 463
 						// don’t cache this
465 464
 						return $cacheMap->toArray();
466 465
 					}
@@ -484,42 +483,42 @@  discard block
 block discarded – undo
484 483
 			]
485 484
 		);
486 485
 
487
-		if ( isset( $cacheMapArray[$textHash] ) ) {
486
+		if (isset($cacheMapArray[$textHash])) {
488 487
 			$key = 'wikibase.quality.constraints.regex.cache.hit';
489
-			$this->dataFactory->increment( $key );
488
+			$this->dataFactory->increment($key);
490 489
 			$matches = $cacheMapArray[$textHash];
491
-			if ( is_bool( $matches ) ) {
490
+			if (is_bool($matches)) {
492 491
 				return $matches;
493
-			} elseif ( is_array( $matches ) &&
494
-				$matches['type'] == ConstraintParameterException::class ) {
495
-				throw $this->deserializeConstraintParameterException( $matches );
492
+			} elseif (is_array($matches) &&
493
+				$matches['type'] == ConstraintParameterException::class) {
494
+				throw $this->deserializeConstraintParameterException($matches);
496 495
 			} else {
497 496
 				throw new MWException(
498
-					'Value of unknown type in object cache (' .
499
-					'cache key: ' . $cacheKey . ', ' .
500
-					'cache map key: ' . $textHash . ', ' .
501
-					'value type: ' . gettype( $matches ) . ')'
497
+					'Value of unknown type in object cache ('.
498
+					'cache key: '.$cacheKey.', '.
499
+					'cache map key: '.$textHash.', '.
500
+					'value type: '.gettype($matches).')'
502 501
 				);
503 502
 			}
504 503
 		} else {
505 504
 			$key = 'wikibase.quality.constraints.regex.cache.miss';
506
-			$this->dataFactory->increment( $key );
507
-			return $this->matchesRegularExpressionWithSparql( $text, $regex );
505
+			$this->dataFactory->increment($key);
506
+			return $this->matchesRegularExpressionWithSparql($text, $regex);
508 507
 		}
509 508
 	}
510 509
 
511
-	private function serializeConstraintParameterException( ConstraintParameterException $cpe ) {
510
+	private function serializeConstraintParameterException(ConstraintParameterException $cpe) {
512 511
 		return [
513 512
 			'type' => ConstraintParameterException::class,
514
-			'violationMessage' => $this->violationMessageSerializer->serialize( $cpe->getViolationMessage() ),
513
+			'violationMessage' => $this->violationMessageSerializer->serialize($cpe->getViolationMessage()),
515 514
 		];
516 515
 	}
517 516
 
518
-	private function deserializeConstraintParameterException( array $serialization ) {
517
+	private function deserializeConstraintParameterException(array $serialization) {
519 518
 		$message = $this->violationMessageDeserializer->deserialize(
520 519
 			$serialization['violationMessage']
521 520
 		);
522
-		return new ConstraintParameterException( $message );
521
+		return new ConstraintParameterException($message);
523 522
 	}
524 523
 
525 524
 	/**
@@ -533,25 +532,25 @@  discard block
 block discarded – undo
533 532
 	 * @throws SparqlHelperException if the query times out or some other error occurs
534 533
 	 * @throws ConstraintParameterException if the $regex is invalid
535 534
 	 */
536
-	public function matchesRegularExpressionWithSparql( $text, $regex ) {
537
-		$textStringLiteral = $this->stringLiteral( $text );
538
-		$regexStringLiteral = $this->stringLiteral( '^(?:' . $regex . ')$' );
535
+	public function matchesRegularExpressionWithSparql($text, $regex) {
536
+		$textStringLiteral = $this->stringLiteral($text);
537
+		$regexStringLiteral = $this->stringLiteral('^(?:'.$regex.')$');
539 538
 
540 539
 		$query = <<<EOF
541 540
 SELECT (REGEX($textStringLiteral, $regexStringLiteral) AS ?matches) {}
542 541
 EOF;
543 542
 
544
-		$result = $this->runQuery( $query, false );
543
+		$result = $this->runQuery($query, false);
545 544
 
546 545
 		$vars = $result->getArray()['results']['bindings'][0];
547
-		if ( array_key_exists( 'matches', $vars ) ) {
546
+		if (array_key_exists('matches', $vars)) {
548 547
 			// true or false ⇒ regex okay, text matches or not
549 548
 			return $vars['matches']['value'] === 'true';
550 549
 		} else {
551 550
 			// empty result: regex broken
552 551
 			throw new ConstraintParameterException(
553
-				( new ViolationMessage( 'wbqc-violation-message-parameter-regex' ) )
554
-					->withInlineCode( $regex, Role::CONSTRAINT_PARAMETER_VALUE )
552
+				(new ViolationMessage('wbqc-violation-message-parameter-regex'))
553
+					->withInlineCode($regex, Role::CONSTRAINT_PARAMETER_VALUE)
555 554
 			);
556 555
 		}
557 556
 	}
@@ -563,14 +562,14 @@  discard block
 block discarded – undo
563 562
 	 *
564 563
 	 * @return boolean
565 564
 	 */
566
-	public function isTimeout( $responseContent ) {
567
-		$timeoutRegex = implode( '|', array_map(
568
-			function ( $fqn ) {
569
-				return preg_quote( $fqn, '/' );
565
+	public function isTimeout($responseContent) {
566
+		$timeoutRegex = implode('|', array_map(
567
+			function($fqn) {
568
+				return preg_quote($fqn, '/');
570 569
 			},
571
-			$this->config->get( 'WBQualityConstraintsSparqlTimeoutExceptionClasses' )
572
-		) );
573
-		return (bool)preg_match( '/' . $timeoutRegex . '/', $responseContent );
570
+			$this->config->get('WBQualityConstraintsSparqlTimeoutExceptionClasses')
571
+		));
572
+		return (bool) preg_match('/'.$timeoutRegex.'/', $responseContent);
574 573
 	}
575 574
 
576 575
 	/**
@@ -582,17 +581,17 @@  discard block
 block discarded – undo
582 581
 	 * @return int|boolean the max-age (in seconds)
583 582
 	 * or a plain boolean if no max-age can be determined
584 583
 	 */
585
-	public function getCacheMaxAge( $responseHeaders ) {
584
+	public function getCacheMaxAge($responseHeaders) {
586 585
 		if (
587
-			array_key_exists( 'x-cache-status', $responseHeaders ) &&
588
-			preg_match( '/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0] )
586
+			array_key_exists('x-cache-status', $responseHeaders) &&
587
+			preg_match('/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0])
589 588
 		) {
590 589
 			$maxage = [];
591 590
 			if (
592
-				array_key_exists( 'cache-control', $responseHeaders ) &&
593
-				preg_match( '/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage )
591
+				array_key_exists('cache-control', $responseHeaders) &&
592
+				preg_match('/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage)
594 593
 			) {
595
-				return intval( $maxage[1] );
594
+				return intval($maxage[1]);
596 595
 			} else {
597 596
 				return true;
598 597
 			}
@@ -614,33 +613,33 @@  discard block
 block discarded – undo
614 613
 	 * or SparlHelper::INVALID_RETRY_AFTER if there is something wrong with the format
615 614
 	 *
616 615
 	 */
617
-	public function getThrottling( array $responseHeaders ) {
618
-		if ( !array_key_exists( 'Retry-After', $responseHeaders ) ) {
616
+	public function getThrottling(array $responseHeaders) {
617
+		if (!array_key_exists('Retry-After', $responseHeaders)) {
619 618
 			return self::NO_RETRY_AFTER;
620 619
 		}
621 620
 
622
-		$trimmedRetryAfterValue = trim( $responseHeaders[ 'Retry-After' ] );
623
-		if ( empty( $trimmedRetryAfterValue ) ) {
621
+		$trimmedRetryAfterValue = trim($responseHeaders['Retry-After']);
622
+		if (empty($trimmedRetryAfterValue)) {
624 623
 			return self::EMPTY_RETRY_AFTER;
625 624
 		}
626 625
 
627
-		if ( is_numeric( $trimmedRetryAfterValue ) ) {
628
-			$delaySeconds = (int)$trimmedRetryAfterValue;
629
-			if ( $delaySeconds >= 0 ) {
630
-				return $this->getTimestampInFuture( new DateInterval( 'PT' . $delaySeconds . 'S' ) );
626
+		if (is_numeric($trimmedRetryAfterValue)) {
627
+			$delaySeconds = (int) $trimmedRetryAfterValue;
628
+			if ($delaySeconds >= 0) {
629
+				return $this->getTimestampInFuture(new DateInterval('PT'.$delaySeconds.'S'));
631 630
 			}
632 631
 		} else {
633
-			$return = strtotime( $responseHeaders[ 'Retry-After' ] );
634
-			if ( !empty( $return ) ) {
635
-				return new ConvertibleTimestamp( $return );
632
+			$return = strtotime($responseHeaders['Retry-After']);
633
+			if (!empty($return)) {
634
+				return new ConvertibleTimestamp($return);
636 635
 			}
637 636
 		}
638 637
 		return self::INVALID_RETRY_AFTER;
639 638
 	}
640 639
 
641
-	private function getTimestampInFuture( DateInterval $delta ) {
640
+	private function getTimestampInFuture(DateInterval $delta) {
642 641
 		$now = new ConvertibleTimestamp();
643
-		return new ConvertibleTimestamp( $now->timestamp->add( $delta ) );
642
+		return new ConvertibleTimestamp($now->timestamp->add($delta));
644 643
 	}
645 644
 
646 645
 	/**
@@ -654,93 +653,92 @@  discard block
 block discarded – undo
654 653
 	 *
655 654
 	 * @throws SparqlHelperException if the query times out or some other error occurs
656 655
 	 */
657
-	public function runQuery( $query, $needsPrefixes = true ) {
656
+	public function runQuery($query, $needsPrefixes = true) {
658 657
 
659
-		if ( $this->throttlingLock->isLocked( self::EXPIRY_LOCK_ID ) ) {
660
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.throttling' );
658
+		if ($this->throttlingLock->isLocked(self::EXPIRY_LOCK_ID)) {
659
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.throttling');
661 660
 			throw new TooManySparqlRequestsException();
662 661
 		}
663 662
 
664
-		$endpoint = $this->config->get( 'WBQualityConstraintsSparqlEndpoint' );
665
-		$maxQueryTimeMillis = $this->config->get( 'WBQualityConstraintsSparqlMaxMillis' );
666
-		$fallbackBlockDuration = (int)$this->config->get( 'WBQualityConstraintsSparqlThrottlingFallbackDuration' );
663
+		$endpoint = $this->config->get('WBQualityConstraintsSparqlEndpoint');
664
+		$maxQueryTimeMillis = $this->config->get('WBQualityConstraintsSparqlMaxMillis');
665
+		$fallbackBlockDuration = (int) $this->config->get('WBQualityConstraintsSparqlThrottlingFallbackDuration');
667 666
 
668
-		if ( $fallbackBlockDuration < 0 ) {
669
-			throw new InvalidArgumentException( 'Fallback duration must be positive int but is: '.
670
-				$fallbackBlockDuration );
667
+		if ($fallbackBlockDuration < 0) {
668
+			throw new InvalidArgumentException('Fallback duration must be positive int but is: '.
669
+				$fallbackBlockDuration);
671 670
 		}
672 671
 
673
-		if ( $needsPrefixes ) {
674
-			$query = $this->prefixes . $query;
672
+		if ($needsPrefixes) {
673
+			$query = $this->prefixes.$query;
675 674
 		}
676
-		$query = "#wbqc\n" . $query;
675
+		$query = "#wbqc\n".$query;
677 676
 
678
-		$url = $endpoint . '?' . http_build_query(
677
+		$url = $endpoint.'?'.http_build_query(
679 678
 			[
680 679
 				'query' => $query,
681 680
 				'format' => 'json',
682 681
 				'maxQueryTimeMillis' => $maxQueryTimeMillis,
683 682
 			],
684
-			null, ini_get( 'arg_separator.output' ),
683
+			null, ini_get('arg_separator.output'),
685 684
 			// encode spaces with %20, not +
686 685
 			PHP_QUERY_RFC3986
687 686
 		);
688 687
 
689 688
 		$options = [
690 689
 			'method' => 'GET',
691
-			'timeout' => (int)round( ( $maxQueryTimeMillis + 1000 ) / 1000 ),
690
+			'timeout' => (int) round(($maxQueryTimeMillis + 1000) / 1000),
692 691
 			'connectTimeout' => 'default',
693 692
 			'userAgent' => $this->defaultUserAgent,
694 693
 		];
695
-		$request = $this->requestFactory->create( $url, $options );
696
-		$startTime = microtime( true );
694
+		$request = $this->requestFactory->create($url, $options);
695
+		$startTime = microtime(true);
697 696
 		$status = $request->execute();
698
-		$endTime = microtime( true );
697
+		$endTime = microtime(true);
699 698
 		$this->dataFactory->timing(
700 699
 			'wikibase.quality.constraints.sparql.timing',
701
-			( $endTime - $startTime ) * 1000
700
+			($endTime - $startTime) * 1000
702 701
 		);
703 702
 
704
-		if ( $request->getStatus() === self::HTTP_TOO_MANY_REQUESTS ) {
705
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.throttling' );
706
-			$throttlingUntil = $this->getThrottling( $request->getResponseHeaders() );
707
-			if ( !( $throttlingUntil instanceof ConvertibleTimestamp ) ) {
708
-				$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid( $request );
703
+		if ($request->getStatus() === self::HTTP_TOO_MANY_REQUESTS) {
704
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.throttling');
705
+			$throttlingUntil = $this->getThrottling($request->getResponseHeaders());
706
+			if (!($throttlingUntil instanceof ConvertibleTimestamp)) {
707
+				$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid($request);
709 708
 				$this->throttlingLock->lock(
710 709
 					self::EXPIRY_LOCK_ID,
711
-					$this->getTimestampInFuture( new DateInterval( 'PT' . $fallbackBlockDuration . 'S' ) )
710
+					$this->getTimestampInFuture(new DateInterval('PT'.$fallbackBlockDuration.'S'))
712 711
 				);
713 712
 			} else {
714
-				$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent( $throttlingUntil, $request );
715
-				$this->throttlingLock->lock( self::EXPIRY_LOCK_ID, $throttlingUntil );
713
+				$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent($throttlingUntil, $request);
714
+				$this->throttlingLock->lock(self::EXPIRY_LOCK_ID, $throttlingUntil);
716 715
 			}
717 716
 			throw new TooManySparqlRequestsException();
718 717
 		}
719 718
 
720
-		$maxAge = $this->getCacheMaxAge( $request->getResponseHeaders() );
721
-		if ( $maxAge ) {
722
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.cached' );
719
+		$maxAge = $this->getCacheMaxAge($request->getResponseHeaders());
720
+		if ($maxAge) {
721
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.cached');
723 722
 		}
724 723
 
725
-		if ( $status->isOK() ) {
724
+		if ($status->isOK()) {
726 725
 			$json = $request->getContent();
727
-			$arr = json_decode( $json, true );
726
+			$arr = json_decode($json, true);
728 727
 			return new CachedQueryResults(
729 728
 				$arr,
730 729
 				Metadata::ofCachingMetadata(
731 730
 					$maxAge ?
732
-						CachingMetadata::ofMaximumAgeInSeconds( $maxAge ) :
733
-						CachingMetadata::fresh()
731
+						CachingMetadata::ofMaximumAgeInSeconds($maxAge) : CachingMetadata::fresh()
734 732
 				)
735 733
 			);
736 734
 		} else {
737
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.error' );
735
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.error');
738 736
 
739 737
 			$this->dataFactory->increment(
740 738
 				"wikibase.quality.constraints.sparql.error.http.{$request->getStatus()}"
741 739
 			);
742 740
 
743
-			if ( $this->isTimeout( $request->getContent() ) ) {
741
+			if ($this->isTimeout($request->getContent())) {
744 742
 				$this->dataFactory->increment(
745 743
 					'wikibase.quality.constraints.sparql.error.timeout'
746 744
 				);
Please login to merge, or discard this patch.