Completed
Push — master ( ac4c6f...74aa43 )
by
unknown
02:33
created
src/ConstraintCheck/Helper/SparqlHelper.php 1 patch
Spacing   +130 added lines, -132 removed lines patch added patch discarded remove patch
@@ -107,18 +107,18 @@  discard block
 block discarded – undo
107 107
 		$this->violationMessageDeserializer = $violationMessageDeserializer;
108 108
 		$this->dataFactory = $dataFactory;
109 109
 
110
-		$this->entityPrefix = $rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_ENTITY );
110
+		$this->entityPrefix = $rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_ENTITY);
111 111
 		$this->prefixes = <<<EOT
112
-PREFIX wd: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_ENTITY )}>
113
-PREFIX wds: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_STATEMENT )}>
114
-PREFIX wdt: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_DIRECT_CLAIM )}>
115
-PREFIX wdv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_VALUE )}>
116
-PREFIX p: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_CLAIM )}>
117
-PREFIX ps: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_CLAIM_STATEMENT )}>
118
-PREFIX pq: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_QUALIFIER )}>
119
-PREFIX pqv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_QUALIFIER_VALUE )}>
120
-PREFIX pr: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_REFERENCE )}>
121
-PREFIX prv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NSP_REFERENCE_VALUE )}>
112
+PREFIX wd: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_ENTITY)}>
113
+PREFIX wds: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_STATEMENT)}>
114
+PREFIX wdt: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_DIRECT_CLAIM)}>
115
+PREFIX wdv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_VALUE)}>
116
+PREFIX p: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_CLAIM)}>
117
+PREFIX ps: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_CLAIM_STATEMENT)}>
118
+PREFIX pq: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_QUALIFIER)}>
119
+PREFIX pqv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_QUALIFIER_VALUE)}>
120
+PREFIX pr: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_REFERENCE)}>
121
+PREFIX prv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NSP_REFERENCE_VALUE)}>
122 122
 PREFIX wikibase: <http://wikiba.se/ontology#>
123 123
 PREFIX wikibase-beta: <http://wikiba.se/ontology-beta#>
124 124
 EOT;
@@ -133,21 +133,21 @@  discard block
 block discarded – undo
133 133
 	 * @return CachedBool
134 134
 	 * @throws SparqlHelperException if the query times out or some other error occurs
135 135
 	 */
136
-	public function hasType( $id, array $classes, $withInstance ) {
137
-		$instanceOfId = $this->config->get( 'WBQualityConstraintsInstanceOfId' );
138
-		$subclassOfId = $this->config->get( 'WBQualityConstraintsSubclassOfId' );
136
+	public function hasType($id, array $classes, $withInstance) {
137
+		$instanceOfId = $this->config->get('WBQualityConstraintsInstanceOfId');
138
+		$subclassOfId = $this->config->get('WBQualityConstraintsSubclassOfId');
139 139
 
140
-		$path = ( $withInstance ? "wdt:$instanceOfId/" : "" ) . "wdt:$subclassOfId*";
140
+		$path = ($withInstance ? "wdt:$instanceOfId/" : "")."wdt:$subclassOfId*";
141 141
 
142 142
 		$metadatas = [];
143 143
 
144
-		foreach ( array_chunk( $classes, 20 ) as $classesChunk ) {
145
-			$classesValues = implode( ' ', array_map(
146
-				function( $class ) {
147
-					return 'wd:' . $class;
144
+		foreach (array_chunk($classes, 20) as $classesChunk) {
145
+			$classesValues = implode(' ', array_map(
146
+				function($class) {
147
+					return 'wd:'.$class;
148 148
 				},
149 149
 				$classesChunk
150
-			) );
150
+			));
151 151
 
152 152
 			$query = <<<EOF
153 153
 ASK {
@@ -158,19 +158,19 @@  discard block
 block discarded – undo
158 158
 EOF;
159 159
 			// TODO hint:gearing is a workaround for T168973 and can hopefully be removed eventually
160 160
 
161
-			$result = $this->runQuery( $query );
161
+			$result = $this->runQuery($query);
162 162
 			$metadatas[] = $result->getMetadata();
163
-			if ( $result->getArray()['boolean'] ) {
163
+			if ($result->getArray()['boolean']) {
164 164
 				return new CachedBool(
165 165
 					true,
166
-					Metadata::merge( $metadatas )
166
+					Metadata::merge($metadatas)
167 167
 				);
168 168
 			}
169 169
 		}
170 170
 
171 171
 		return new CachedBool(
172 172
 			false,
173
-			Metadata::merge( $metadatas )
173
+			Metadata::merge($metadatas)
174 174
 		);
175 175
 	}
176 176
 
@@ -186,10 +186,10 @@  discard block
 block discarded – undo
186 186
 		$ignoreDeprecatedStatements
187 187
 	) {
188 188
 		$pid = $statement->getPropertyId()->serialize();
189
-		$guid = str_replace( '$', '-', $statement->getGuid() );
189
+		$guid = str_replace('$', '-', $statement->getGuid());
190 190
 
191 191
 		$deprecatedFilter = '';
192
-		if ( $ignoreDeprecatedStatements ) {
192
+		if ($ignoreDeprecatedStatements) {
193 193
 			$deprecatedFilter .= 'MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. }';
194 194
 			$deprecatedFilter .= 'MINUS { ?otherStatement wikibase-beta:rank wikibase-beta:DeprecatedRank. }';
195 195
 		}
@@ -209,9 +209,9 @@  discard block
 block discarded – undo
209 209
 LIMIT 10
210 210
 EOF;
211 211
 
212
-		$result = $this->runQuery( $query );
212
+		$result = $this->runQuery($query);
213 213
 
214
-		return $this->getOtherEntities( $result );
214
+		return $this->getOtherEntities($result);
215 215
 	}
216 216
 
217 217
 	/**
@@ -236,16 +236,15 @@  discard block
 block discarded – undo
236 236
 		$dataType = $this->propertyDataTypeLookup->getDataTypeIdForProperty(
237 237
 			$snak->getPropertyId()
238 238
 		);
239
-		list( $value, $isFullValue ) = $this->getRdfLiteral( $dataType, $dataValue );
240
-		if ( $isFullValue ) {
239
+		list($value, $isFullValue) = $this->getRdfLiteral($dataType, $dataValue);
240
+		if ($isFullValue) {
241 241
 			$prefix .= 'v';
242 242
 		}
243 243
 		$path = $type === Context::TYPE_QUALIFIER ?
244
-			"$prefix:$pid" :
245
-			"prov:wasDerivedFrom/$prefix:$pid";
244
+			"$prefix:$pid" : "prov:wasDerivedFrom/$prefix:$pid";
246 245
 
247 246
 		$deprecatedFilter = '';
248
-		if ( $ignoreDeprecatedStatements ) {
247
+		if ($ignoreDeprecatedStatements) {
249 248
 			$deprecatedFilter = <<< EOF
250 249
   MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. }
251 250
   MINUS { ?otherStatement wikibase-beta:rank wikibase-beta:DeprecatedRank. }
@@ -266,9 +265,9 @@  discard block
 block discarded – undo
266 265
 LIMIT 10
267 266
 EOF;
268 267
 
269
-		$result = $this->runQuery( $query );
268
+		$result = $this->runQuery($query);
270 269
 
271
-		return $this->getOtherEntities( $result );
270
+		return $this->getOtherEntities($result);
272 271
 	}
273 272
 
274 273
 	/**
@@ -278,8 +277,8 @@  discard block
 block discarded – undo
278 277
 	 *
279 278
 	 * @return string
280 279
 	 */
281
-	private function stringLiteral( $text ) {
282
-		return '"' . strtr( $text, [ '"' => '\\"', '\\' => '\\\\' ] ) . '"';
280
+	private function stringLiteral($text) {
281
+		return '"'.strtr($text, ['"' => '\\"', '\\' => '\\\\']).'"';
283 282
 	}
284 283
 
285 284
 	/**
@@ -289,17 +288,17 @@  discard block
 block discarded – undo
289 288
 	 *
290 289
 	 * @return CachedEntityIds
291 290
 	 */
292
-	private function getOtherEntities( CachedQueryResults $results ) {
293
-		return new CachedEntityIds( array_map(
294
-			function ( $resultBindings ) {
291
+	private function getOtherEntities(CachedQueryResults $results) {
292
+		return new CachedEntityIds(array_map(
293
+			function($resultBindings) {
295 294
 				$entityIRI = $resultBindings['otherEntity']['value'];
296
-				$entityPrefixLength = strlen( $this->entityPrefix );
297
-				if ( substr( $entityIRI, 0, $entityPrefixLength ) === $this->entityPrefix ) {
295
+				$entityPrefixLength = strlen($this->entityPrefix);
296
+				if (substr($entityIRI, 0, $entityPrefixLength) === $this->entityPrefix) {
298 297
 					try {
299 298
 						return $this->entityIdParser->parse(
300
-							substr( $entityIRI, $entityPrefixLength )
299
+							substr($entityIRI, $entityPrefixLength)
301 300
 						);
302
-					} catch ( EntityIdParsingException $e ) {
301
+					} catch (EntityIdParsingException $e) {
303 302
 						// fall through
304 303
 					}
305 304
 				}
@@ -307,7 +306,7 @@  discard block
 block discarded – undo
307 306
 				return null;
308 307
 			},
309 308
 			$results->getArray()['results']['bindings']
310
-		), $results->getMetadata() );
309
+		), $results->getMetadata());
311 310
 	}
312 311
 
313 312
 	// @codingStandardsIgnoreStart cyclomatic complexity of this function is too high
@@ -320,47 +319,47 @@  discard block
 block discarded – undo
320 319
 	 * @return array the literal or IRI as a string in SPARQL syntax,
321 320
 	 * and a boolean indicating whether it refers to a full value node or not
322 321
 	 */
323
-	private function getRdfLiteral( $dataType, DataValue $dataValue ) {
324
-		switch ( $dataType ) {
322
+	private function getRdfLiteral($dataType, DataValue $dataValue) {
323
+		switch ($dataType) {
325 324
 			case 'string':
326 325
 			case 'external-id':
327
-				return [ $this->stringLiteral( $dataValue->getValue() ), false ];
326
+				return [$this->stringLiteral($dataValue->getValue()), false];
328 327
 			case 'commonsMedia':
329
-				$url = $this->rdfVocabulary->getMediaFileURI( $dataValue->getValue() );
330
-				return [ '<' . $url . '>', false ];
328
+				$url = $this->rdfVocabulary->getMediaFileURI($dataValue->getValue());
329
+				return ['<'.$url.'>', false];
331 330
 			case 'geo-shape':
332
-				$url = $this->rdfVocabulary->getGeoShapeURI( $dataValue->getValue() );
333
-				return [ '<' . $url . '>', false ];
331
+				$url = $this->rdfVocabulary->getGeoShapeURI($dataValue->getValue());
332
+				return ['<'.$url.'>', false];
334 333
 			case 'tabular-data':
335
-				$url = $this->rdfVocabulary->getTabularDataURI( $dataValue->getValue() );
336
-				return [ '<' . $url . '>', false ];
334
+				$url = $this->rdfVocabulary->getTabularDataURI($dataValue->getValue());
335
+				return ['<'.$url.'>', false];
337 336
 			case 'url':
338 337
 				$url = $dataValue->getValue();
339
-				if ( !preg_match( '/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url ) ) {
338
+				if (!preg_match('/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url)) {
340 339
 					// not a valid URL for SPARQL (see SPARQL spec, production 139 IRIREF)
341 340
 					// such an URL should never reach us, so just throw
342
-					throw new InvalidArgumentException( 'invalid URL: ' . $url );
341
+					throw new InvalidArgumentException('invalid URL: '.$url);
343 342
 				}
344
-				return [ '<' . $url . '>', false ];
343
+				return ['<'.$url.'>', false];
345 344
 			case 'wikibase-item':
346 345
 			case 'wikibase-property':
347 346
 				/** @var EntityIdValue $dataValue */
348
-				return [ 'wd:' . $dataValue->getEntityId()->getSerialization(), false ];
347
+				return ['wd:'.$dataValue->getEntityId()->getSerialization(), false];
349 348
 			case 'monolingualtext':
350 349
 				/** @var MonolingualTextValue $dataValue */
351 350
 				$lang = $dataValue->getLanguageCode();
352
-				if ( !preg_match( '/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang ) ) {
351
+				if (!preg_match('/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang)) {
353 352
 					// not a valid language tag for SPARQL (see SPARQL spec, production 145 LANGTAG)
354 353
 					// such a language tag should never reach us, so just throw
355
-					throw new InvalidArgumentException( 'invalid language tag: ' . $lang );
354
+					throw new InvalidArgumentException('invalid language tag: '.$lang);
356 355
 				}
357
-				return [ $this->stringLiteral( $dataValue->getText() ) . '@' . $lang, false ];
356
+				return [$this->stringLiteral($dataValue->getText()).'@'.$lang, false];
358 357
 			case 'globe-coordinate':
359 358
 			case 'quantity':
360 359
 			case 'time':
361
-				return [ 'wdv:' . $dataValue->getHash(), true ];
360
+				return ['wdv:'.$dataValue->getHash(), true];
362 361
 			default:
363
-				throw new InvalidArgumentException( 'unknown data type: ' . $dataType );
362
+				throw new InvalidArgumentException('unknown data type: '.$dataType);
364 363
 		}
365 364
 	}
366 365
 	// @codingStandardsIgnoreEnd
@@ -373,47 +372,47 @@  discard block
 block discarded – undo
373 372
 	 * @throws SparqlHelperException if the query times out or some other error occurs
374 373
 	 * @throws ConstraintParameterException if the $regex is invalid
375 374
 	 */
376
-	public function matchesRegularExpression( $text, $regex ) {
375
+	public function matchesRegularExpression($text, $regex) {
377 376
 		// caching wrapper around matchesRegularExpressionWithSparql
378 377
 
379
-		$textHash = hash( 'sha256', $text );
378
+		$textHash = hash('sha256', $text);
380 379
 		$cacheKey = $this->cache->makeKey(
381 380
 			'WikibaseQualityConstraints', // extension
382 381
 			'regex', // action
383 382
 			'WDQS-Java', // regex flavor
384
-			hash( 'sha256', $regex )
383
+			hash('sha256', $regex)
385 384
 		);
386
-		$cacheMapSize = $this->config->get( 'WBQualityConstraintsFormatCacheMapSize' );
385
+		$cacheMapSize = $this->config->get('WBQualityConstraintsFormatCacheMapSize');
387 386
 
388 387
 		$cacheMapArray = $this->cache->getWithSetCallback(
389 388
 			$cacheKey,
390 389
 			WANObjectCache::TTL_DAY,
391
-			function( $cacheMapArray ) use ( $text, $regex, $textHash, $cacheMapSize ) {
390
+			function($cacheMapArray) use ($text, $regex, $textHash, $cacheMapSize) {
392 391
 				// Initialize the cache map if not set
393
-				if ( $cacheMapArray === false ) {
392
+				if ($cacheMapArray === false) {
394 393
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.init';
395
-					$this->dataFactory->increment( $key );
394
+					$this->dataFactory->increment($key);
396 395
 					return [];
397 396
 				}
398 397
 
399 398
 				$key = 'wikibase.quality.constraints.regex.cache.refresh';
400
-				$this->dataFactory->increment( $key );
401
-				$cacheMap = MapCacheLRU::newFromArray( $cacheMapArray, $cacheMapSize );
402
-				if ( $cacheMap->has( $textHash ) ) {
399
+				$this->dataFactory->increment($key);
400
+				$cacheMap = MapCacheLRU::newFromArray($cacheMapArray, $cacheMapSize);
401
+				if ($cacheMap->has($textHash)) {
403 402
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.hit';
404
-					$this->dataFactory->increment( $key );
405
-					$cacheMap->get( $textHash ); // ping cache
403
+					$this->dataFactory->increment($key);
404
+					$cacheMap->get($textHash); // ping cache
406 405
 				} else {
407 406
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.miss';
408
-					$this->dataFactory->increment( $key );
407
+					$this->dataFactory->increment($key);
409 408
 					try {
410
-						$matches = $this->matchesRegularExpressionWithSparql( $text, $regex );
411
-					} catch ( ConstraintParameterException $e ) {
409
+						$matches = $this->matchesRegularExpressionWithSparql($text, $regex);
410
+					} catch (ConstraintParameterException $e) {
412 411
 						$matches = [
413 412
 							'type' => ConstraintParameterException::class,
414 413
 							'message' => $e->getMessage(),
415 414
 						];
416
-					} catch ( SparqlHelperException $e ) {
415
+					} catch (SparqlHelperException $e) {
417 416
 						// don’t cache this
418 417
 						return $cacheMap->toArray();
419 418
 					}
@@ -437,27 +436,27 @@  discard block
 block discarded – undo
437 436
 			]
438 437
 		);
439 438
 
440
-		if ( isset( $cacheMapArray[$textHash] ) ) {
439
+		if (isset($cacheMapArray[$textHash])) {
441 440
 			$key = 'wikibase.quality.constraints.regex.cache.hit';
442
-			$this->dataFactory->increment( $key );
441
+			$this->dataFactory->increment($key);
443 442
 			$matches = $cacheMapArray[$textHash];
444
-			if ( is_bool( $matches ) ) {
443
+			if (is_bool($matches)) {
445 444
 				return $matches;
446
-			} elseif ( is_array( $matches ) &&
447
-				$matches['type'] == ConstraintParameterException::class ) {
448
-				throw new ConstraintParameterException( $matches['message'] );
445
+			} elseif (is_array($matches) &&
446
+				$matches['type'] == ConstraintParameterException::class) {
447
+				throw new ConstraintParameterException($matches['message']);
449 448
 			} else {
450 449
 				throw new MWException(
451
-					'Value of unknown type in object cache (' .
452
-					'cache key: ' . $cacheKey . ', ' .
453
-					'cache map key: ' . $textHash . ', ' .
454
-					'value type: ' . gettype( $matches ) . ')'
450
+					'Value of unknown type in object cache ('.
451
+					'cache key: '.$cacheKey.', '.
452
+					'cache map key: '.$textHash.', '.
453
+					'value type: '.gettype($matches).')'
455 454
 				);
456 455
 			}
457 456
 		} else {
458 457
 			$key = 'wikibase.quality.constraints.regex.cache.miss';
459
-			$this->dataFactory->increment( $key );
460
-			return $this->matchesRegularExpressionWithSparql( $text, $regex );
458
+			$this->dataFactory->increment($key);
459
+			return $this->matchesRegularExpressionWithSparql($text, $regex);
461 460
 		}
462 461
 	}
463 462
 
@@ -472,26 +471,26 @@  discard block
 block discarded – undo
472 471
 	 * @throws SparqlHelperException if the query times out or some other error occurs
473 472
 	 * @throws ConstraintParameterException if the $regex is invalid
474 473
 	 */
475
-	public function matchesRegularExpressionWithSparql( $text, $regex ) {
476
-		$textStringLiteral = $this->stringLiteral( $text );
477
-		$regexStringLiteral = $this->stringLiteral( '^' . $regex . '$' );
474
+	public function matchesRegularExpressionWithSparql($text, $regex) {
475
+		$textStringLiteral = $this->stringLiteral($text);
476
+		$regexStringLiteral = $this->stringLiteral('^'.$regex.'$');
478 477
 
479 478
 		$query = <<<EOF
480 479
 SELECT (REGEX($textStringLiteral, $regexStringLiteral) AS ?matches) {}
481 480
 EOF;
482 481
 
483
-		$result = $this->runQuery( $query );
482
+		$result = $this->runQuery($query);
484 483
 
485 484
 		$vars = $result->getArray()['results']['bindings'][0];
486
-		if ( array_key_exists( 'matches', $vars ) ) {
485
+		if (array_key_exists('matches', $vars)) {
487 486
 			// true or false ⇒ regex okay, text matches or not
488 487
 			return $vars['matches']['value'] === 'true';
489 488
 		} else {
490 489
 			// empty result: regex broken
491 490
 			throw new ConstraintParameterException(
492
-				wfMessage( 'wbqc-violation-message-parameter-regex' )
493
-					->rawParams( ConstraintParameterRenderer::formatByRole( Role::CONSTRAINT_PARAMETER_VALUE,
494
-						'<code><nowiki>' . htmlspecialchars( $regex ) . '</nowiki></code>' ) )
491
+				wfMessage('wbqc-violation-message-parameter-regex')
492
+					->rawParams(ConstraintParameterRenderer::formatByRole(Role::CONSTRAINT_PARAMETER_VALUE,
493
+						'<code><nowiki>'.htmlspecialchars($regex).'</nowiki></code>'))
495 494
 					->escaped()
496 495
 			);
497 496
 		}
@@ -504,14 +503,14 @@  discard block
 block discarded – undo
504 503
 	 *
505 504
 	 * @return boolean
506 505
 	 */
507
-	public function isTimeout( $responseContent ) {
508
-		$timeoutRegex = implode( '|', array_map(
509
-			function ( $fqn ) {
510
-				return preg_quote( $fqn, '/' );
506
+	public function isTimeout($responseContent) {
507
+		$timeoutRegex = implode('|', array_map(
508
+			function($fqn) {
509
+				return preg_quote($fqn, '/');
511 510
 			},
512
-			$this->config->get( 'WBQualityConstraintsSparqlTimeoutExceptionClasses' )
513
-		) );
514
-		return (bool)preg_match( '/' . $timeoutRegex . '/', $responseContent );
511
+			$this->config->get('WBQualityConstraintsSparqlTimeoutExceptionClasses')
512
+		));
513
+		return (bool) preg_match('/'.$timeoutRegex.'/', $responseContent);
515 514
 	}
516 515
 
517 516
 	/**
@@ -523,17 +522,17 @@  discard block
 block discarded – undo
523 522
 	 * @return integer|boolean the max-age (in seconds)
524 523
 	 * or a plain boolean if no max-age can be determined
525 524
 	 */
526
-	public function getCacheMaxAge( $responseHeaders ) {
525
+	public function getCacheMaxAge($responseHeaders) {
527 526
 		if (
528
-			array_key_exists( 'x-cache-status', $responseHeaders ) &&
529
-			preg_match( '/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0] )
527
+			array_key_exists('x-cache-status', $responseHeaders) &&
528
+			preg_match('/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0])
530 529
 		) {
531 530
 			$maxage = [];
532 531
 			if (
533
-				array_key_exists( 'cache-control', $responseHeaders ) &&
534
-				preg_match( '/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage )
532
+				array_key_exists('cache-control', $responseHeaders) &&
533
+				preg_match('/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage)
535 534
 			) {
536
-				return intval( $maxage[1] );
535
+				return intval($maxage[1]);
537 536
 			} else {
538 537
 				return true;
539 538
 			}
@@ -551,59 +550,58 @@  discard block
 block discarded – undo
551 550
 	 *
552 551
 	 * @throws SparqlHelperException if the query times out or some other error occurs
553 552
 	 */
554
-	public function runQuery( $query ) {
553
+	public function runQuery($query) {
555 554
 
556
-		$endpoint = $this->config->get( 'WBQualityConstraintsSparqlEndpoint' );
557
-		$maxQueryTimeMillis = $this->config->get( 'WBQualityConstraintsSparqlMaxMillis' );
558
-		$url = $endpoint . '?' . http_build_query(
555
+		$endpoint = $this->config->get('WBQualityConstraintsSparqlEndpoint');
556
+		$maxQueryTimeMillis = $this->config->get('WBQualityConstraintsSparqlMaxMillis');
557
+		$url = $endpoint.'?'.http_build_query(
559 558
 			[
560
-				'query' => "#wbqc\n" . $this->prefixes . $query,
559
+				'query' => "#wbqc\n".$this->prefixes.$query,
561 560
 				'format' => 'json',
562 561
 				'maxQueryTimeMillis' => $maxQueryTimeMillis,
563 562
 			],
564
-			null, ini_get( 'arg_separator.output' ),
563
+			null, ini_get('arg_separator.output'),
565 564
 			// encode spaces with %20, not +
566 565
 			PHP_QUERY_RFC3986
567 566
 		);
568 567
 
569 568
 		$options = [
570 569
 			'method' => 'GET',
571
-			'timeout' => (int)round( ( $maxQueryTimeMillis + 1000 ) / 1000 ),
570
+			'timeout' => (int) round(($maxQueryTimeMillis + 1000) / 1000),
572 571
 			'connectTimeout' => 'default',
573 572
 		];
574
-		$request = MWHttpRequest::factory( $url, $options );
575
-		$startTime = microtime( true );
573
+		$request = MWHttpRequest::factory($url, $options);
574
+		$startTime = microtime(true);
576 575
 		$status = $request->execute();
577
-		$endTime = microtime( true );
576
+		$endTime = microtime(true);
578 577
 		$this->dataFactory->timing(
579 578
 			'wikibase.quality.constraints.sparql.timing',
580
-			( $endTime - $startTime ) * 1000
579
+			($endTime - $startTime) * 1000
581 580
 		);
582 581
 
583
-		$maxAge = $this->getCacheMaxAge( $request->getResponseHeaders() );
584
-		if ( $maxAge ) {
585
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.cached' );
582
+		$maxAge = $this->getCacheMaxAge($request->getResponseHeaders());
583
+		if ($maxAge) {
584
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.cached');
586 585
 		}
587 586
 
588
-		if ( $status->isOK() ) {
587
+		if ($status->isOK()) {
589 588
 			$json = $request->getContent();
590
-			$arr = json_decode( $json, true );
589
+			$arr = json_decode($json, true);
591 590
 			return new CachedQueryResults(
592 591
 				$arr,
593 592
 				Metadata::ofCachingMetadata(
594 593
 					$maxAge ?
595
-						CachingMetadata::ofMaximumAgeInSeconds( $maxAge ) :
596
-						CachingMetadata::fresh()
594
+						CachingMetadata::ofMaximumAgeInSeconds($maxAge) : CachingMetadata::fresh()
597 595
 				)
598 596
 			);
599 597
 		} else {
600
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.error' );
598
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.error');
601 599
 
602 600
 			$this->dataFactory->increment(
603 601
 				"wikibase.quality.constraints.sparql.error.http.{$request->getStatus()}"
604 602
 			);
605 603
 
606
-			if ( $this->isTimeout( $request->getContent() ) ) {
604
+			if ($this->isTimeout($request->getContent())) {
607 605
 				$this->dataFactory->increment(
608 606
 					'wikibase.quality.constraints.sparql.error.timeout'
609 607
 				);
Please login to merge, or discard this patch.