Completed
Push — master ( 5784e1...353732 )
by
unknown
12:47
created
src/ConstraintCheck/Helper/SparqlHelper.php 1 patch
Spacing   +136 added lines, -138 removed lines patch added patch discarded remove patch
@@ -120,18 +120,18 @@  discard block
 block discarded – undo
120 120
 		$this->dataFactory = $dataFactory;
121 121
 		$this->defaultUserAgent = $defaultUserAgent;
122 122
 		$this->requestFactory = $requestFactory;
123
-		$this->entityPrefix = $rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_ENTITY );
123
+		$this->entityPrefix = $rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_ENTITY);
124 124
 		$this->prefixes = <<<EOT
125
-PREFIX wd: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_ENTITY )}>
126
-PREFIX wds: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_STATEMENT )}>
127
-PREFIX wdt: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_DIRECT_CLAIM )}>
128
-PREFIX wdv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_VALUE )}>
129
-PREFIX p: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_CLAIM )}>
130
-PREFIX ps: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_CLAIM_STATEMENT )}>
131
-PREFIX pq: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_QUALIFIER )}>
132
-PREFIX pqv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_QUALIFIER_VALUE )}>
133
-PREFIX pr: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_REFERENCE )}>
134
-PREFIX prv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_REFERENCE_VALUE )}>
125
+PREFIX wd: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_ENTITY)}>
126
+PREFIX wds: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_STATEMENT)}>
127
+PREFIX wdt: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_DIRECT_CLAIM)}>
128
+PREFIX wdv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_VALUE)}>
129
+PREFIX p: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_CLAIM)}>
130
+PREFIX ps: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_CLAIM_STATEMENT)}>
131
+PREFIX pq: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_QUALIFIER)}>
132
+PREFIX pqv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_QUALIFIER_VALUE)}>
133
+PREFIX pr: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_REFERENCE)}>
134
+PREFIX prv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_REFERENCE_VALUE)}>
135 135
 PREFIX wikibase: <http://wikiba.se/ontology#>
136 136
 PREFIX wikibase-beta: <http://wikiba.se/ontology-beta#>
137 137
 EOT;
@@ -146,21 +146,21 @@  discard block
 block discarded – undo
146 146
 	 * @return CachedBool
147 147
 	 * @throws SparqlHelperException if the query times out or some other error occurs
148 148
 	 */
149
-	public function hasType( $id, array $classes, $withInstance ) {
150
-		$instanceOfId = $this->config->get( 'WBQualityConstraintsInstanceOfId' );
151
-		$subclassOfId = $this->config->get( 'WBQualityConstraintsSubclassOfId' );
149
+	public function hasType($id, array $classes, $withInstance) {
150
+		$instanceOfId = $this->config->get('WBQualityConstraintsInstanceOfId');
151
+		$subclassOfId = $this->config->get('WBQualityConstraintsSubclassOfId');
152 152
 
153
-		$path = ( $withInstance ? "wdt:$instanceOfId/" : "" ) . "wdt:$subclassOfId*";
153
+		$path = ($withInstance ? "wdt:$instanceOfId/" : "")."wdt:$subclassOfId*";
154 154
 
155 155
 		$metadatas = [];
156 156
 
157
-		foreach ( array_chunk( $classes, 20 ) as $classesChunk ) {
158
-			$classesValues = implode( ' ', array_map(
159
-				function( $class ) {
160
-					return 'wd:' . $class;
157
+		foreach (array_chunk($classes, 20) as $classesChunk) {
158
+			$classesValues = implode(' ', array_map(
159
+				function($class) {
160
+					return 'wd:'.$class;
161 161
 				},
162 162
 				$classesChunk
163
-			) );
163
+			));
164 164
 
165 165
 			$query = <<<EOF
166 166
 ASK {
@@ -171,19 +171,19 @@  discard block
 block discarded – undo
171 171
 EOF;
172 172
 			// TODO hint:gearing is a workaround for T168973 and can hopefully be removed eventually
173 173
 
174
-			$result = $this->runQuery( $query );
174
+			$result = $this->runQuery($query);
175 175
 			$metadatas[] = $result->getMetadata();
176
-			if ( $result->getArray()['boolean'] ) {
176
+			if ($result->getArray()['boolean']) {
177 177
 				return new CachedBool(
178 178
 					true,
179
-					Metadata::merge( $metadatas )
179
+					Metadata::merge($metadatas)
180 180
 				);
181 181
 			}
182 182
 		}
183 183
 
184 184
 		return new CachedBool(
185 185
 			false,
186
-			Metadata::merge( $metadatas )
186
+			Metadata::merge($metadatas)
187 187
 		);
188 188
 	}
189 189
 
@@ -199,10 +199,10 @@  discard block
 block discarded – undo
199 199
 		$ignoreDeprecatedStatements
200 200
 	) {
201 201
 		$pid = $statement->getPropertyId()->serialize();
202
-		$guid = str_replace( '$', '-', $statement->getGuid() );
202
+		$guid = str_replace('$', '-', $statement->getGuid());
203 203
 
204 204
 		$deprecatedFilter = '';
205
-		if ( $ignoreDeprecatedStatements ) {
205
+		if ($ignoreDeprecatedStatements) {
206 206
 			$deprecatedFilter .= 'MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. }';
207 207
 			$deprecatedFilter .= 'MINUS { ?otherStatement wikibase-beta:rank wikibase-beta:DeprecatedRank. }';
208 208
 		}
@@ -222,9 +222,9 @@  discard block
 block discarded – undo
222 222
 LIMIT 10
223 223
 EOF;
224 224
 
225
-		$result = $this->runQuery( $query );
225
+		$result = $this->runQuery($query);
226 226
 
227
-		return $this->getOtherEntities( $result );
227
+		return $this->getOtherEntities($result);
228 228
 	}
229 229
 
230 230
 	/**
@@ -249,16 +249,15 @@  discard block
 block discarded – undo
249 249
 		$dataType = $this->propertyDataTypeLookup->getDataTypeIdForProperty(
250 250
 			$snak->getPropertyId()
251 251
 		);
252
-		list( $value, $isFullValue ) = $this->getRdfLiteral( $dataType, $dataValue );
253
-		if ( $isFullValue ) {
252
+		list($value, $isFullValue) = $this->getRdfLiteral($dataType, $dataValue);
253
+		if ($isFullValue) {
254 254
 			$prefix .= 'v';
255 255
 		}
256 256
 		$path = $type === Context::TYPE_QUALIFIER ?
257
-			"$prefix:$pid" :
258
-			"prov:wasDerivedFrom/$prefix:$pid";
257
+			"$prefix:$pid" : "prov:wasDerivedFrom/$prefix:$pid";
259 258
 
260 259
 		$deprecatedFilter = '';
261
-		if ( $ignoreDeprecatedStatements ) {
260
+		if ($ignoreDeprecatedStatements) {
262 261
 			$deprecatedFilter = <<< EOF
263 262
   MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. }
264 263
   MINUS { ?otherStatement wikibase-beta:rank wikibase-beta:DeprecatedRank. }
@@ -279,9 +278,9 @@  discard block
 block discarded – undo
279 278
 LIMIT 10
280 279
 EOF;
281 280
 
282
-		$result = $this->runQuery( $query );
281
+		$result = $this->runQuery($query);
283 282
 
284
-		return $this->getOtherEntities( $result );
283
+		return $this->getOtherEntities($result);
285 284
 	}
286 285
 
287 286
 	/**
@@ -291,8 +290,8 @@  discard block
 block discarded – undo
291 290
 	 *
292 291
 	 * @return string
293 292
 	 */
294
-	private function stringLiteral( $text ) {
295
-		return '"' . strtr( $text, [ '"' => '\\"', '\\' => '\\\\' ] ) . '"';
293
+	private function stringLiteral($text) {
294
+		return '"'.strtr($text, ['"' => '\\"', '\\' => '\\\\']).'"';
296 295
 	}
297 296
 
298 297
 	/**
@@ -302,17 +301,17 @@  discard block
 block discarded – undo
302 301
 	 *
303 302
 	 * @return CachedEntityIds
304 303
 	 */
305
-	private function getOtherEntities( CachedQueryResults $results ) {
306
-		return new CachedEntityIds( array_map(
307
-			function ( $resultBindings ) {
304
+	private function getOtherEntities(CachedQueryResults $results) {
305
+		return new CachedEntityIds(array_map(
306
+			function($resultBindings) {
308 307
 				$entityIRI = $resultBindings['otherEntity']['value'];
309
-				$entityPrefixLength = strlen( $this->entityPrefix );
310
-				if ( substr( $entityIRI, 0, $entityPrefixLength ) === $this->entityPrefix ) {
308
+				$entityPrefixLength = strlen($this->entityPrefix);
309
+				if (substr($entityIRI, 0, $entityPrefixLength) === $this->entityPrefix) {
311 310
 					try {
312 311
 						return $this->entityIdParser->parse(
313
-							substr( $entityIRI, $entityPrefixLength )
312
+							substr($entityIRI, $entityPrefixLength)
314 313
 						);
315
-					} catch ( EntityIdParsingException $e ) {
314
+					} catch (EntityIdParsingException $e) {
316 315
 						// fall through
317 316
 					}
318 317
 				}
@@ -320,7 +319,7 @@  discard block
 block discarded – undo
320 319
 				return null;
321 320
 			},
322 321
 			$results->getArray()['results']['bindings']
323
-		), $results->getMetadata() );
322
+		), $results->getMetadata());
324 323
 	}
325 324
 
326 325
 	// @codingStandardsIgnoreStart cyclomatic complexity of this function is too high
@@ -333,47 +332,47 @@  discard block
 block discarded – undo
333 332
 	 * @return array the literal or IRI as a string in SPARQL syntax,
334 333
 	 * and a boolean indicating whether it refers to a full value node or not
335 334
 	 */
336
-	private function getRdfLiteral( $dataType, DataValue $dataValue ) {
337
-		switch ( $dataType ) {
335
+	private function getRdfLiteral($dataType, DataValue $dataValue) {
336
+		switch ($dataType) {
338 337
 			case 'string':
339 338
 			case 'external-id':
340
-				return [ $this->stringLiteral( $dataValue->getValue() ), false ];
339
+				return [$this->stringLiteral($dataValue->getValue()), false];
341 340
 			case 'commonsMedia':
342
-				$url = $this->rdfVocabulary->getMediaFileURI( $dataValue->getValue() );
343
-				return [ '<' . $url . '>', false ];
341
+				$url = $this->rdfVocabulary->getMediaFileURI($dataValue->getValue());
342
+				return ['<'.$url.'>', false];
344 343
 			case 'geo-shape':
345
-				$url = $this->rdfVocabulary->getGeoShapeURI( $dataValue->getValue() );
346
-				return [ '<' . $url . '>', false ];
344
+				$url = $this->rdfVocabulary->getGeoShapeURI($dataValue->getValue());
345
+				return ['<'.$url.'>', false];
347 346
 			case 'tabular-data':
348
-				$url = $this->rdfVocabulary->getTabularDataURI( $dataValue->getValue() );
349
-				return [ '<' . $url . '>', false ];
347
+				$url = $this->rdfVocabulary->getTabularDataURI($dataValue->getValue());
348
+				return ['<'.$url.'>', false];
350 349
 			case 'url':
351 350
 				$url = $dataValue->getValue();
352
-				if ( !preg_match( '/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url ) ) {
351
+				if (!preg_match('/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url)) {
353 352
 					// not a valid URL for SPARQL (see SPARQL spec, production 139 IRIREF)
354 353
 					// such an URL should never reach us, so just throw
355
-					throw new InvalidArgumentException( 'invalid URL: ' . $url );
354
+					throw new InvalidArgumentException('invalid URL: '.$url);
356 355
 				}
357
-				return [ '<' . $url . '>', false ];
356
+				return ['<'.$url.'>', false];
358 357
 			case 'wikibase-item':
359 358
 			case 'wikibase-property':
360 359
 				/** @var EntityIdValue $dataValue */
361
-				return [ 'wd:' . $dataValue->getEntityId()->getSerialization(), false ];
360
+				return ['wd:'.$dataValue->getEntityId()->getSerialization(), false];
362 361
 			case 'monolingualtext':
363 362
 				/** @var MonolingualTextValue $dataValue */
364 363
 				$lang = $dataValue->getLanguageCode();
365
-				if ( !preg_match( '/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang ) ) {
364
+				if (!preg_match('/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang)) {
366 365
 					// not a valid language tag for SPARQL (see SPARQL spec, production 145 LANGTAG)
367 366
 					// such a language tag should never reach us, so just throw
368
-					throw new InvalidArgumentException( 'invalid language tag: ' . $lang );
367
+					throw new InvalidArgumentException('invalid language tag: '.$lang);
369 368
 				}
370
-				return [ $this->stringLiteral( $dataValue->getText() ) . '@' . $lang, false ];
369
+				return [$this->stringLiteral($dataValue->getText()).'@'.$lang, false];
371 370
 			case 'globe-coordinate':
372 371
 			case 'quantity':
373 372
 			case 'time':
374
-				return [ 'wdv:' . $dataValue->getHash(), true ];
373
+				return ['wdv:'.$dataValue->getHash(), true];
375 374
 			default:
376
-				throw new InvalidArgumentException( 'unknown data type: ' . $dataType );
375
+				throw new InvalidArgumentException('unknown data type: '.$dataType);
377 376
 		}
378 377
 	}
379 378
 	// @codingStandardsIgnoreEnd
@@ -386,44 +385,44 @@  discard block
 block discarded – undo
386 385
 	 * @throws SparqlHelperException if the query times out or some other error occurs
387 386
 	 * @throws ConstraintParameterException if the $regex is invalid
388 387
 	 */
389
-	public function matchesRegularExpression( $text, $regex ) {
388
+	public function matchesRegularExpression($text, $regex) {
390 389
 		// caching wrapper around matchesRegularExpressionWithSparql
391 390
 
392
-		$textHash = hash( 'sha256', $text );
391
+		$textHash = hash('sha256', $text);
393 392
 		$cacheKey = $this->cache->makeKey(
394 393
 			'WikibaseQualityConstraints', // extension
395 394
 			'regex', // action
396 395
 			'WDQS-Java', // regex flavor
397
-			hash( 'sha256', $regex )
396
+			hash('sha256', $regex)
398 397
 		);
399
-		$cacheMapSize = $this->config->get( 'WBQualityConstraintsFormatCacheMapSize' );
398
+		$cacheMapSize = $this->config->get('WBQualityConstraintsFormatCacheMapSize');
400 399
 
401 400
 		$cacheMapArray = $this->cache->getWithSetCallback(
402 401
 			$cacheKey,
403 402
 			WANObjectCache::TTL_DAY,
404
-			function( $cacheMapArray ) use ( $text, $regex, $textHash, $cacheMapSize ) {
403
+			function($cacheMapArray) use ($text, $regex, $textHash, $cacheMapSize) {
405 404
 				// Initialize the cache map if not set
406
-				if ( $cacheMapArray === false ) {
405
+				if ($cacheMapArray === false) {
407 406
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.init';
408
-					$this->dataFactory->increment( $key );
407
+					$this->dataFactory->increment($key);
409 408
 					return [];
410 409
 				}
411 410
 
412 411
 				$key = 'wikibase.quality.constraints.regex.cache.refresh';
413
-				$this->dataFactory->increment( $key );
414
-				$cacheMap = MapCacheLRU::newFromArray( $cacheMapArray, $cacheMapSize );
415
-				if ( $cacheMap->has( $textHash ) ) {
412
+				$this->dataFactory->increment($key);
413
+				$cacheMap = MapCacheLRU::newFromArray($cacheMapArray, $cacheMapSize);
414
+				if ($cacheMap->has($textHash)) {
416 415
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.hit';
417
-					$this->dataFactory->increment( $key );
418
-					$cacheMap->get( $textHash ); // ping cache
416
+					$this->dataFactory->increment($key);
417
+					$cacheMap->get($textHash); // ping cache
419 418
 				} else {
420 419
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.miss';
421
-					$this->dataFactory->increment( $key );
420
+					$this->dataFactory->increment($key);
422 421
 					try {
423
-						$matches = $this->matchesRegularExpressionWithSparql( $text, $regex );
424
-					} catch ( ConstraintParameterException $e ) {
425
-						$matches = $this->serializeConstraintParameterException( $e );
426
-					} catch ( SparqlHelperException $e ) {
422
+						$matches = $this->matchesRegularExpressionWithSparql($text, $regex);
423
+					} catch (ConstraintParameterException $e) {
424
+						$matches = $this->serializeConstraintParameterException($e);
425
+					} catch (SparqlHelperException $e) {
427 426
 						// don’t cache this
428 427
 						return $cacheMap->toArray();
429 428
 					}
@@ -447,42 +446,42 @@  discard block
 block discarded – undo
447 446
 			]
448 447
 		);
449 448
 
450
-		if ( isset( $cacheMapArray[$textHash] ) ) {
449
+		if (isset($cacheMapArray[$textHash])) {
451 450
 			$key = 'wikibase.quality.constraints.regex.cache.hit';
452
-			$this->dataFactory->increment( $key );
451
+			$this->dataFactory->increment($key);
453 452
 			$matches = $cacheMapArray[$textHash];
454
-			if ( is_bool( $matches ) ) {
453
+			if (is_bool($matches)) {
455 454
 				return $matches;
456
-			} elseif ( is_array( $matches ) &&
457
-				$matches['type'] == ConstraintParameterException::class ) {
458
-				throw $this->deserializeConstraintParameterException( $matches );
455
+			} elseif (is_array($matches) &&
456
+				$matches['type'] == ConstraintParameterException::class) {
457
+				throw $this->deserializeConstraintParameterException($matches);
459 458
 			} else {
460 459
 				throw new MWException(
461
-					'Value of unknown type in object cache (' .
462
-					'cache key: ' . $cacheKey . ', ' .
463
-					'cache map key: ' . $textHash . ', ' .
464
-					'value type: ' . gettype( $matches ) . ')'
460
+					'Value of unknown type in object cache ('.
461
+					'cache key: '.$cacheKey.', '.
462
+					'cache map key: '.$textHash.', '.
463
+					'value type: '.gettype($matches).')'
465 464
 				);
466 465
 			}
467 466
 		} else {
468 467
 			$key = 'wikibase.quality.constraints.regex.cache.miss';
469
-			$this->dataFactory->increment( $key );
470
-			return $this->matchesRegularExpressionWithSparql( $text, $regex );
468
+			$this->dataFactory->increment($key);
469
+			return $this->matchesRegularExpressionWithSparql($text, $regex);
471 470
 		}
472 471
 	}
473 472
 
474
-	private function serializeConstraintParameterException( ConstraintParameterException $cpe ) {
473
+	private function serializeConstraintParameterException(ConstraintParameterException $cpe) {
475 474
 		return [
476 475
 			'type' => ConstraintParameterException::class,
477
-			'violationMessage' => $this->violationMessageSerializer->serialize( $cpe->getViolationMessage() ),
476
+			'violationMessage' => $this->violationMessageSerializer->serialize($cpe->getViolationMessage()),
478 477
 		];
479 478
 	}
480 479
 
481
-	private function deserializeConstraintParameterException( array $serialization ) {
480
+	private function deserializeConstraintParameterException(array $serialization) {
482 481
 		$message = $this->violationMessageDeserializer->deserialize(
483 482
 			$serialization['violationMessage']
484 483
 		);
485
-		return new ConstraintParameterException( $message );
484
+		return new ConstraintParameterException($message);
486 485
 	}
487 486
 
488 487
 	/**
@@ -496,25 +495,25 @@  discard block
 block discarded – undo
496 495
 	 * @throws SparqlHelperException if the query times out or some other error occurs
497 496
 	 * @throws ConstraintParameterException if the $regex is invalid
498 497
 	 */
499
-	public function matchesRegularExpressionWithSparql( $text, $regex ) {
500
-		$textStringLiteral = $this->stringLiteral( $text );
501
-		$regexStringLiteral = $this->stringLiteral( '^(?:' . $regex . ')$' );
498
+	public function matchesRegularExpressionWithSparql($text, $regex) {
499
+		$textStringLiteral = $this->stringLiteral($text);
500
+		$regexStringLiteral = $this->stringLiteral('^(?:'.$regex.')$');
502 501
 
503 502
 		$query = <<<EOF
504 503
 SELECT (REGEX($textStringLiteral, $regexStringLiteral) AS ?matches) {}
505 504
 EOF;
506 505
 
507
-		$result = $this->runQuery( $query, false );
506
+		$result = $this->runQuery($query, false);
508 507
 
509 508
 		$vars = $result->getArray()['results']['bindings'][0];
510
-		if ( array_key_exists( 'matches', $vars ) ) {
509
+		if (array_key_exists('matches', $vars)) {
511 510
 			// true or false ⇒ regex okay, text matches or not
512 511
 			return $vars['matches']['value'] === 'true';
513 512
 		} else {
514 513
 			// empty result: regex broken
515 514
 			throw new ConstraintParameterException(
516
-				( new ViolationMessage( 'wbqc-violation-message-parameter-regex' ) )
517
-					->withInlineCode( $regex, Role::CONSTRAINT_PARAMETER_VALUE )
515
+				(new ViolationMessage('wbqc-violation-message-parameter-regex'))
516
+					->withInlineCode($regex, Role::CONSTRAINT_PARAMETER_VALUE)
518 517
 			);
519 518
 		}
520 519
 	}
@@ -526,14 +525,14 @@  discard block
 block discarded – undo
526 525
 	 *
527 526
 	 * @return boolean
528 527
 	 */
529
-	public function isTimeout( $responseContent ) {
530
-		$timeoutRegex = implode( '|', array_map(
531
-			function ( $fqn ) {
532
-				return preg_quote( $fqn, '/' );
528
+	public function isTimeout($responseContent) {
529
+		$timeoutRegex = implode('|', array_map(
530
+			function($fqn) {
531
+				return preg_quote($fqn, '/');
533 532
 			},
534
-			$this->config->get( 'WBQualityConstraintsSparqlTimeoutExceptionClasses' )
535
-		) );
536
-		return (bool)preg_match( '/' . $timeoutRegex . '/', $responseContent );
533
+			$this->config->get('WBQualityConstraintsSparqlTimeoutExceptionClasses')
534
+		));
535
+		return (bool) preg_match('/'.$timeoutRegex.'/', $responseContent);
537 536
 	}
538 537
 
539 538
 	/**
@@ -545,17 +544,17 @@  discard block
 block discarded – undo
545 544
 	 * @return integer|boolean the max-age (in seconds)
546 545
 	 * or a plain boolean if no max-age can be determined
547 546
 	 */
548
-	public function getCacheMaxAge( $responseHeaders ) {
547
+	public function getCacheMaxAge($responseHeaders) {
549 548
 		if (
550
-			array_key_exists( 'x-cache-status', $responseHeaders ) &&
551
-			preg_match( '/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0] )
549
+			array_key_exists('x-cache-status', $responseHeaders) &&
550
+			preg_match('/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0])
552 551
 		) {
553 552
 			$maxage = [];
554 553
 			if (
555
-				array_key_exists( 'cache-control', $responseHeaders ) &&
556
-				preg_match( '/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage )
554
+				array_key_exists('cache-control', $responseHeaders) &&
555
+				preg_match('/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage)
557 556
 			) {
558
-				return intval( $maxage[1] );
557
+				return intval($maxage[1]);
559 558
 			} else {
560 559
 				return true;
561 560
 			}
@@ -574,65 +573,64 @@  discard block
 block discarded – undo
574 573
 	 *
575 574
 	 * @throws SparqlHelperException if the query times out or some other error occurs
576 575
 	 */
577
-	public function runQuery( $query, $needsPrefixes = true ) {
578
-		$endpoint = $this->config->get( 'WBQualityConstraintsSparqlEndpoint' );
579
-		$maxQueryTimeMillis = $this->config->get( 'WBQualityConstraintsSparqlMaxMillis' );
576
+	public function runQuery($query, $needsPrefixes = true) {
577
+		$endpoint = $this->config->get('WBQualityConstraintsSparqlEndpoint');
578
+		$maxQueryTimeMillis = $this->config->get('WBQualityConstraintsSparqlMaxMillis');
580 579
 
581
-		if ( $needsPrefixes ) {
582
-			$query = $this->prefixes . $query;
580
+		if ($needsPrefixes) {
581
+			$query = $this->prefixes.$query;
583 582
 		}
584
-		$query = "#wbqc\n" . $query;
583
+		$query = "#wbqc\n".$query;
585 584
 
586
-		$url = $endpoint . '?' . http_build_query(
585
+		$url = $endpoint.'?'.http_build_query(
587 586
 			[
588 587
 				'query' => $query,
589 588
 				'format' => 'json',
590 589
 				'maxQueryTimeMillis' => $maxQueryTimeMillis,
591 590
 			],
592
-			null, ini_get( 'arg_separator.output' ),
591
+			null, ini_get('arg_separator.output'),
593 592
 			// encode spaces with %20, not +
594 593
 			PHP_QUERY_RFC3986
595 594
 		);
596 595
 
597 596
 		$options = [
598 597
 			'method' => 'GET',
599
-			'timeout' => (int)round( ( $maxQueryTimeMillis + 1000 ) / 1000 ),
598
+			'timeout' => (int) round(($maxQueryTimeMillis + 1000) / 1000),
600 599
 			'connectTimeout' => 'default',
601 600
 			'userAgent' => $this->defaultUserAgent,
602 601
 		];
603
-		$request = $this->requestFactory->create( $url, $options );
604
-		$startTime = microtime( true );
602
+		$request = $this->requestFactory->create($url, $options);
603
+		$startTime = microtime(true);
605 604
 		$status = $request->execute();
606
-		$endTime = microtime( true );
605
+		$endTime = microtime(true);
607 606
 		$this->dataFactory->timing(
608 607
 			'wikibase.quality.constraints.sparql.timing',
609
-			( $endTime - $startTime ) * 1000
608
+			($endTime - $startTime) * 1000
610 609
 		);
611 610
 
612
-		$maxAge = $this->getCacheMaxAge( $request->getResponseHeaders() );
613
-		if ( $maxAge ) {
614
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.cached' );
611
+		$maxAge = $this->getCacheMaxAge($request->getResponseHeaders());
612
+		if ($maxAge) {
613
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.cached');
615 614
 		}
616 615
 
617
-		if ( $status->isOK() ) {
616
+		if ($status->isOK()) {
618 617
 			$json = $request->getContent();
619
-			$arr = json_decode( $json, true );
618
+			$arr = json_decode($json, true);
620 619
 			return new CachedQueryResults(
621 620
 				$arr,
622 621
 				Metadata::ofCachingMetadata(
623 622
 					$maxAge ?
624
-						CachingMetadata::ofMaximumAgeInSeconds( $maxAge ) :
625
-						CachingMetadata::fresh()
623
+						CachingMetadata::ofMaximumAgeInSeconds($maxAge) : CachingMetadata::fresh()
626 624
 				)
627 625
 			);
628 626
 		} else {
629
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.error' );
627
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.error');
630 628
 
631 629
 			$this->dataFactory->increment(
632 630
 				"wikibase.quality.constraints.sparql.error.http.{$request->getStatus()}"
633 631
 			);
634 632
 
635
-			if ( $this->isTimeout( $request->getContent() ) ) {
633
+			if ($this->isTimeout($request->getContent())) {
636 634
 				$this->dataFactory->increment(
637 635
 					'wikibase.quality.constraints.sparql.error.timeout'
638 636
 				);
Please login to merge, or discard this patch.