@@ -200,73 +200,73 @@ discard block |
||
200 | 200 | $this->defaultUserAgent = $defaultUserAgent; |
201 | 201 | $this->requestFactory = $requestFactory; |
202 | 202 | $this->entityPrefixes = []; |
203 | - foreach ( $rdfVocabulary->entityNamespaceNames as $namespaceName ) { |
|
204 | - $this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI( $namespaceName ); |
|
203 | + foreach ($rdfVocabulary->entityNamespaceNames as $namespaceName) { |
|
204 | + $this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI($namespaceName); |
|
205 | 205 | } |
206 | 206 | |
207 | - $this->endpoint = $config->get( 'WBQualityConstraintsSparqlEndpoint' ); |
|
208 | - $this->maxQueryTimeMillis = $config->get( 'WBQualityConstraintsSparqlMaxMillis' ); |
|
209 | - $this->instanceOfId = $config->get( 'WBQualityConstraintsInstanceOfId' ); |
|
210 | - $this->subclassOfId = $config->get( 'WBQualityConstraintsSubclassOfId' ); |
|
211 | - $this->cacheMapSize = $config->get( 'WBQualityConstraintsFormatCacheMapSize' ); |
|
207 | + $this->endpoint = $config->get('WBQualityConstraintsSparqlEndpoint'); |
|
208 | + $this->maxQueryTimeMillis = $config->get('WBQualityConstraintsSparqlMaxMillis'); |
|
209 | + $this->instanceOfId = $config->get('WBQualityConstraintsInstanceOfId'); |
|
210 | + $this->subclassOfId = $config->get('WBQualityConstraintsSubclassOfId'); |
|
211 | + $this->cacheMapSize = $config->get('WBQualityConstraintsFormatCacheMapSize'); |
|
212 | 212 | $this->timeoutExceptionClasses = $config->get( |
213 | 213 | 'WBQualityConstraintsSparqlTimeoutExceptionClasses' |
214 | 214 | ); |
215 | 215 | $this->sparqlHasWikibaseSupport = $config->get( |
216 | 216 | 'WBQualityConstraintsSparqlHasWikibaseSupport' |
217 | 217 | ); |
218 | - $this->sparqlThrottlingFallbackDuration = (int)$config->get( |
|
218 | + $this->sparqlThrottlingFallbackDuration = (int) $config->get( |
|
219 | 219 | 'WBQualityConstraintsSparqlThrottlingFallbackDuration' |
220 | 220 | ); |
221 | 221 | |
222 | - $this->prefixes = $this->getQueryPrefixes( $rdfVocabulary ); |
|
222 | + $this->prefixes = $this->getQueryPrefixes($rdfVocabulary); |
|
223 | 223 | } |
224 | 224 | |
225 | - private function getQueryPrefixes( RdfVocabulary $rdfVocabulary ) { |
|
225 | + private function getQueryPrefixes(RdfVocabulary $rdfVocabulary) { |
|
226 | 226 | // TODO: it would probably be smarter that RdfVocubulary exposed these prefixes somehow |
227 | 227 | $prefixes = ''; |
228 | - foreach ( $rdfVocabulary->entityNamespaceNames as $sourceName => $namespaceName ) { |
|
228 | + foreach ($rdfVocabulary->entityNamespaceNames as $sourceName => $namespaceName) { |
|
229 | 229 | $prefixes .= <<<END |
230 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
230 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
231 | 231 | END; |
232 | 232 | } |
233 | 233 | $prefixes .= <<<END |
234 | -PREFIX wds: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_STATEMENT )}> |
|
235 | -PREFIX wdv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_VALUE )}>\n |
|
234 | +PREFIX wds: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_STATEMENT)}> |
|
235 | +PREFIX wdv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_VALUE)}>\n |
|
236 | 236 | END; |
237 | 237 | |
238 | - foreach ( $rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces ) { |
|
238 | + foreach ($rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces) { |
|
239 | 239 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_DIRECT_CLAIM]; |
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_CLAIM]; |
244 | 244 | $prefixes .= <<<END |
245 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
245 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
246 | 246 | END; |
247 | 247 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM_STATEMENT]; |
248 | 248 | $prefixes .= <<<END |
249 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
249 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
250 | 250 | END; |
251 | 251 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER]; |
252 | 252 | $prefixes .= <<<END |
253 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
253 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
254 | 254 | END; |
255 | 255 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER_VALUE]; |
256 | 256 | $prefixes .= <<<END |
257 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
257 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
258 | 258 | END; |
259 | 259 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE]; |
260 | 260 | $prefixes .= <<<END |
261 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
261 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
262 | 262 | END; |
263 | 263 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE_VALUE]; |
264 | 264 | $prefixes .= <<<END |
265 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
265 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
266 | 266 | END; |
267 | 267 | } |
268 | 268 | $prefixes .= <<<END |
269 | -PREFIX wikibase: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_ONTOLOGY )}>\n |
|
269 | +PREFIX wikibase: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_ONTOLOGY)}>\n |
|
270 | 270 | END; |
271 | 271 | return $prefixes; |
272 | 272 | } |
@@ -278,21 +278,20 @@ discard block |
||
278 | 278 | * @return CachedBool |
279 | 279 | * @throws SparqlHelperException if the query times out or some other error occurs |
280 | 280 | */ |
281 | - public function hasType( $id, array $classes ) { |
|
281 | + public function hasType($id, array $classes) { |
|
282 | 282 | // TODO hint:gearing is a workaround for T168973 and can hopefully be removed eventually |
283 | 283 | $gearingHint = $this->sparqlHasWikibaseSupport ? |
284 | - ' hint:Prior hint:gearing "forward".' : |
|
285 | - ''; |
|
284 | + ' hint:Prior hint:gearing "forward".' : ''; |
|
286 | 285 | |
287 | 286 | $metadatas = []; |
288 | 287 | |
289 | - foreach ( array_chunk( $classes, 20 ) as $classesChunk ) { |
|
290 | - $classesValues = implode( ' ', array_map( |
|
291 | - static function ( $class ) { |
|
292 | - return 'wd:' . $class; |
|
288 | + foreach (array_chunk($classes, 20) as $classesChunk) { |
|
289 | + $classesValues = implode(' ', array_map( |
|
290 | + static function($class) { |
|
291 | + return 'wd:'.$class; |
|
293 | 292 | }, |
294 | 293 | $classesChunk |
295 | - ) ); |
|
294 | + )); |
|
296 | 295 | |
297 | 296 | $query = <<<EOF |
298 | 297 | ASK { |
@@ -302,19 +301,19 @@ discard block |
||
302 | 301 | } |
303 | 302 | EOF; |
304 | 303 | |
305 | - $result = $this->runQuery( $query ); |
|
304 | + $result = $this->runQuery($query); |
|
306 | 305 | $metadatas[] = $result->getMetadata(); |
307 | - if ( $result->getArray()['boolean'] ) { |
|
306 | + if ($result->getArray()['boolean']) { |
|
308 | 307 | return new CachedBool( |
309 | 308 | true, |
310 | - Metadata::merge( $metadatas ) |
|
309 | + Metadata::merge($metadatas) |
|
311 | 310 | ); |
312 | 311 | } |
313 | 312 | } |
314 | 313 | |
315 | 314 | return new CachedBool( |
316 | 315 | false, |
317 | - Metadata::merge( $metadatas ) |
|
316 | + Metadata::merge($metadatas) |
|
318 | 317 | ); |
319 | 318 | } |
320 | 319 | |
@@ -325,7 +324,7 @@ discard block |
||
325 | 324 | * @param PropertyId $separator |
326 | 325 | * @return string |
327 | 326 | */ |
328 | - private function nestedSeparatorFilter( PropertyId $separator ) { |
|
327 | + private function nestedSeparatorFilter(PropertyId $separator) { |
|
329 | 328 | $filter = <<<EOF |
330 | 329 | MINUS { |
331 | 330 | ?statement pq:$separator ?qualifier. |
@@ -369,10 +368,10 @@ discard block |
||
369 | 368 | $pid = $statement->getPropertyId()->getSerialization(); |
370 | 369 | $guid = $statement->getGuid(); |
371 | 370 | '@phan-var string $guid'; // statement must have a non-null GUID |
372 | - $guidForRdf = str_replace( '$', '-', $guid ); |
|
371 | + $guidForRdf = str_replace('$', '-', $guid); |
|
373 | 372 | |
374 | - $separatorFilters = array_map( [ $this, 'nestedSeparatorFilter' ], $separators ); |
|
375 | - $finalSeparatorFilter = implode( "\n", $separatorFilters ); |
|
373 | + $separatorFilters = array_map([$this, 'nestedSeparatorFilter'], $separators); |
|
374 | + $finalSeparatorFilter = implode("\n", $separatorFilters); |
|
376 | 375 | |
377 | 376 | $query = <<<EOF |
378 | 377 | SELECT DISTINCT ?otherEntity WHERE { |
@@ -390,9 +389,9 @@ discard block |
||
390 | 389 | LIMIT 10 |
391 | 390 | EOF; |
392 | 391 | |
393 | - $result = $this->runQuery( $query ); |
|
392 | + $result = $this->runQuery($query); |
|
394 | 393 | |
395 | - return $this->getOtherEntities( $result ); |
|
394 | + return $this->getOtherEntities($result); |
|
396 | 395 | } |
397 | 396 | |
398 | 397 | /** |
@@ -417,16 +416,15 @@ discard block |
||
417 | 416 | $dataType = $this->propertyDataTypeLookup->getDataTypeIdForProperty( |
418 | 417 | $snak->getPropertyId() |
419 | 418 | ); |
420 | - list( $value, $isFullValue ) = $this->getRdfLiteral( $dataType, $dataValue ); |
|
421 | - if ( $isFullValue ) { |
|
419 | + list($value, $isFullValue) = $this->getRdfLiteral($dataType, $dataValue); |
|
420 | + if ($isFullValue) { |
|
422 | 421 | $prefix .= 'v'; |
423 | 422 | } |
424 | 423 | $path = $type === Context::TYPE_QUALIFIER ? |
425 | - "$prefix:$pid" : |
|
426 | - "prov:wasDerivedFrom/$prefix:$pid"; |
|
424 | + "$prefix:$pid" : "prov:wasDerivedFrom/$prefix:$pid"; |
|
427 | 425 | |
428 | 426 | $deprecatedFilter = ''; |
429 | - if ( $ignoreDeprecatedStatements ) { |
|
427 | + if ($ignoreDeprecatedStatements) { |
|
430 | 428 | $deprecatedFilter = <<< EOF |
431 | 429 | MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. } |
432 | 430 | EOF; |
@@ -446,9 +444,9 @@ discard block |
||
446 | 444 | LIMIT 10 |
447 | 445 | EOF; |
448 | 446 | |
449 | - $result = $this->runQuery( $query ); |
|
447 | + $result = $this->runQuery($query); |
|
450 | 448 | |
451 | - return $this->getOtherEntities( $result ); |
|
449 | + return $this->getOtherEntities($result); |
|
452 | 450 | } |
453 | 451 | |
454 | 452 | /** |
@@ -458,8 +456,8 @@ discard block |
||
458 | 456 | * |
459 | 457 | * @return string |
460 | 458 | */ |
461 | - private function stringLiteral( $text ) { |
|
462 | - return '"' . strtr( $text, [ '"' => '\\"', '\\' => '\\\\' ] ) . '"'; |
|
459 | + private function stringLiteral($text) { |
|
460 | + return '"'.strtr($text, ['"' => '\\"', '\\' => '\\\\']).'"'; |
|
463 | 461 | } |
464 | 462 | |
465 | 463 | /** |
@@ -469,18 +467,18 @@ discard block |
||
469 | 467 | * |
470 | 468 | * @return CachedEntityIds |
471 | 469 | */ |
472 | - private function getOtherEntities( CachedQueryResults $results ) { |
|
473 | - return new CachedEntityIds( array_map( |
|
474 | - function ( $resultBindings ) { |
|
470 | + private function getOtherEntities(CachedQueryResults $results) { |
|
471 | + return new CachedEntityIds(array_map( |
|
472 | + function($resultBindings) { |
|
475 | 473 | $entityIRI = $resultBindings['otherEntity']['value']; |
476 | - foreach ( $this->entityPrefixes as $entityPrefix ) { |
|
477 | - $entityPrefixLength = strlen( $entityPrefix ); |
|
478 | - if ( substr( $entityIRI, 0, $entityPrefixLength ) === $entityPrefix ) { |
|
474 | + foreach ($this->entityPrefixes as $entityPrefix) { |
|
475 | + $entityPrefixLength = strlen($entityPrefix); |
|
476 | + if (substr($entityIRI, 0, $entityPrefixLength) === $entityPrefix) { |
|
479 | 477 | try { |
480 | 478 | return $this->entityIdParser->parse( |
481 | - substr( $entityIRI, $entityPrefixLength ) |
|
479 | + substr($entityIRI, $entityPrefixLength) |
|
482 | 480 | ); |
483 | - } catch ( EntityIdParsingException $e ) { |
|
481 | + } catch (EntityIdParsingException $e) { |
|
484 | 482 | // fall through |
485 | 483 | } |
486 | 484 | } |
@@ -491,7 +489,7 @@ discard block |
||
491 | 489 | return null; |
492 | 490 | }, |
493 | 491 | $results->getArray()['results']['bindings'] |
494 | - ), $results->getMetadata() ); |
|
492 | + ), $results->getMetadata()); |
|
495 | 493 | } |
496 | 494 | |
497 | 495 | // phpcs:disable Generic.Metrics.CyclomaticComplexity,Squiz.WhiteSpace.FunctionSpacing |
@@ -504,50 +502,50 @@ discard block |
||
504 | 502 | * @return array the literal or IRI as a string in SPARQL syntax, |
505 | 503 | * and a boolean indicating whether it refers to a full value node or not |
506 | 504 | */ |
507 | - private function getRdfLiteral( $dataType, DataValue $dataValue ) { |
|
508 | - switch ( $dataType ) { |
|
505 | + private function getRdfLiteral($dataType, DataValue $dataValue) { |
|
506 | + switch ($dataType) { |
|
509 | 507 | case 'string': |
510 | 508 | case 'external-id': |
511 | - return [ $this->stringLiteral( $dataValue->getValue() ), false ]; |
|
509 | + return [$this->stringLiteral($dataValue->getValue()), false]; |
|
512 | 510 | case 'commonsMedia': |
513 | - $url = $this->rdfVocabulary->getMediaFileURI( $dataValue->getValue() ); |
|
514 | - return [ '<' . $url . '>', false ]; |
|
511 | + $url = $this->rdfVocabulary->getMediaFileURI($dataValue->getValue()); |
|
512 | + return ['<'.$url.'>', false]; |
|
515 | 513 | case 'geo-shape': |
516 | - $url = $this->rdfVocabulary->getGeoShapeURI( $dataValue->getValue() ); |
|
517 | - return [ '<' . $url . '>', false ]; |
|
514 | + $url = $this->rdfVocabulary->getGeoShapeURI($dataValue->getValue()); |
|
515 | + return ['<'.$url.'>', false]; |
|
518 | 516 | case 'tabular-data': |
519 | - $url = $this->rdfVocabulary->getTabularDataURI( $dataValue->getValue() ); |
|
520 | - return [ '<' . $url . '>', false ]; |
|
517 | + $url = $this->rdfVocabulary->getTabularDataURI($dataValue->getValue()); |
|
518 | + return ['<'.$url.'>', false]; |
|
521 | 519 | case 'url': |
522 | 520 | $url = $dataValue->getValue(); |
523 | - if ( !preg_match( '/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url ) ) { |
|
521 | + if (!preg_match('/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url)) { |
|
524 | 522 | // not a valid URL for SPARQL (see SPARQL spec, production 139 IRIREF) |
525 | 523 | // such an URL should never reach us, so just throw |
526 | - throw new InvalidArgumentException( 'invalid URL: ' . $url ); |
|
524 | + throw new InvalidArgumentException('invalid URL: '.$url); |
|
527 | 525 | } |
528 | - return [ '<' . $url . '>', false ]; |
|
526 | + return ['<'.$url.'>', false]; |
|
529 | 527 | case 'wikibase-item': |
530 | 528 | case 'wikibase-property': |
531 | 529 | /** @var EntityIdValue $dataValue */ |
532 | 530 | '@phan-var EntityIdValue $dataValue'; |
533 | - return [ 'wd:' . $dataValue->getEntityId()->getSerialization(), false ]; |
|
531 | + return ['wd:'.$dataValue->getEntityId()->getSerialization(), false]; |
|
534 | 532 | case 'monolingualtext': |
535 | 533 | /** @var MonolingualTextValue $dataValue */ |
536 | 534 | '@phan-var MonolingualTextValue $dataValue'; |
537 | 535 | $lang = $dataValue->getLanguageCode(); |
538 | - if ( !preg_match( '/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang ) ) { |
|
536 | + if (!preg_match('/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang)) { |
|
539 | 537 | // not a valid language tag for SPARQL (see SPARQL spec, production 145 LANGTAG) |
540 | 538 | // such a language tag should never reach us, so just throw |
541 | - throw new InvalidArgumentException( 'invalid language tag: ' . $lang ); |
|
539 | + throw new InvalidArgumentException('invalid language tag: '.$lang); |
|
542 | 540 | } |
543 | - return [ $this->stringLiteral( $dataValue->getText() ) . '@' . $lang, false ]; |
|
541 | + return [$this->stringLiteral($dataValue->getText()).'@'.$lang, false]; |
|
544 | 542 | case 'globe-coordinate': |
545 | 543 | case 'quantity': |
546 | 544 | case 'time': |
547 | 545 | // @phan-suppress-next-line PhanUndeclaredMethod |
548 | - return [ 'wdv:' . $dataValue->getHash(), true ]; |
|
546 | + return ['wdv:'.$dataValue->getHash(), true]; |
|
549 | 547 | default: |
550 | - throw new InvalidArgumentException( 'unknown data type: ' . $dataType ); |
|
548 | + throw new InvalidArgumentException('unknown data type: '.$dataType); |
|
551 | 549 | } |
552 | 550 | } |
553 | 551 | // phpcs:enable |
@@ -560,43 +558,43 @@ discard block |
||
560 | 558 | * @throws SparqlHelperException if the query times out or some other error occurs |
561 | 559 | * @throws ConstraintParameterException if the $regex is invalid |
562 | 560 | */ |
563 | - public function matchesRegularExpression( $text, $regex ) { |
|
561 | + public function matchesRegularExpression($text, $regex) { |
|
564 | 562 | // caching wrapper around matchesRegularExpressionWithSparql |
565 | 563 | |
566 | - $textHash = hash( 'sha256', $text ); |
|
564 | + $textHash = hash('sha256', $text); |
|
567 | 565 | $cacheKey = $this->cache->makeKey( |
568 | 566 | 'WikibaseQualityConstraints', // extension |
569 | 567 | 'regex', // action |
570 | 568 | 'WDQS-Java', // regex flavor |
571 | - hash( 'sha256', $regex ) |
|
569 | + hash('sha256', $regex) |
|
572 | 570 | ); |
573 | 571 | |
574 | 572 | $cacheMapArray = $this->cache->getWithSetCallback( |
575 | 573 | $cacheKey, |
576 | 574 | WANObjectCache::TTL_DAY, |
577 | - function ( $cacheMapArray ) use ( $text, $regex, $textHash ) { |
|
575 | + function($cacheMapArray) use ($text, $regex, $textHash) { |
|
578 | 576 | // Initialize the cache map if not set |
579 | - if ( $cacheMapArray === false ) { |
|
577 | + if ($cacheMapArray === false) { |
|
580 | 578 | $key = 'wikibase.quality.constraints.regex.cache.refresh.init'; |
581 | - $this->dataFactory->increment( $key ); |
|
579 | + $this->dataFactory->increment($key); |
|
582 | 580 | return []; |
583 | 581 | } |
584 | 582 | |
585 | 583 | $key = 'wikibase.quality.constraints.regex.cache.refresh'; |
586 | - $this->dataFactory->increment( $key ); |
|
587 | - $cacheMap = MapCacheLRU::newFromArray( $cacheMapArray, $this->cacheMapSize ); |
|
588 | - if ( $cacheMap->has( $textHash ) ) { |
|
584 | + $this->dataFactory->increment($key); |
|
585 | + $cacheMap = MapCacheLRU::newFromArray($cacheMapArray, $this->cacheMapSize); |
|
586 | + if ($cacheMap->has($textHash)) { |
|
589 | 587 | $key = 'wikibase.quality.constraints.regex.cache.refresh.hit'; |
590 | - $this->dataFactory->increment( $key ); |
|
591 | - $cacheMap->get( $textHash ); // ping cache |
|
588 | + $this->dataFactory->increment($key); |
|
589 | + $cacheMap->get($textHash); // ping cache |
|
592 | 590 | } else { |
593 | 591 | $key = 'wikibase.quality.constraints.regex.cache.refresh.miss'; |
594 | - $this->dataFactory->increment( $key ); |
|
592 | + $this->dataFactory->increment($key); |
|
595 | 593 | try { |
596 | - $matches = $this->matchesRegularExpressionWithSparql( $text, $regex ); |
|
597 | - } catch ( ConstraintParameterException $e ) { |
|
598 | - $matches = $this->serializeConstraintParameterException( $e ); |
|
599 | - } catch ( SparqlHelperException $e ) { |
|
594 | + $matches = $this->matchesRegularExpressionWithSparql($text, $regex); |
|
595 | + } catch (ConstraintParameterException $e) { |
|
596 | + $matches = $this->serializeConstraintParameterException($e); |
|
597 | + } catch (SparqlHelperException $e) { |
|
600 | 598 | // don’t cache this |
601 | 599 | return $cacheMap->toArray(); |
602 | 600 | } |
@@ -620,42 +618,42 @@ discard block |
||
620 | 618 | ] |
621 | 619 | ); |
622 | 620 | |
623 | - if ( isset( $cacheMapArray[$textHash] ) ) { |
|
621 | + if (isset($cacheMapArray[$textHash])) { |
|
624 | 622 | $key = 'wikibase.quality.constraints.regex.cache.hit'; |
625 | - $this->dataFactory->increment( $key ); |
|
623 | + $this->dataFactory->increment($key); |
|
626 | 624 | $matches = $cacheMapArray[$textHash]; |
627 | - if ( is_bool( $matches ) ) { |
|
625 | + if (is_bool($matches)) { |
|
628 | 626 | return $matches; |
629 | - } elseif ( is_array( $matches ) && |
|
630 | - $matches['type'] == ConstraintParameterException::class ) { |
|
631 | - throw $this->deserializeConstraintParameterException( $matches ); |
|
627 | + } elseif (is_array($matches) && |
|
628 | + $matches['type'] == ConstraintParameterException::class) { |
|
629 | + throw $this->deserializeConstraintParameterException($matches); |
|
632 | 630 | } else { |
633 | 631 | throw new UnexpectedValueException( |
634 | - 'Value of unknown type in object cache (' . |
|
635 | - 'cache key: ' . $cacheKey . ', ' . |
|
636 | - 'cache map key: ' . $textHash . ', ' . |
|
637 | - 'value type: ' . gettype( $matches ) . ')' |
|
632 | + 'Value of unknown type in object cache ('. |
|
633 | + 'cache key: '.$cacheKey.', '. |
|
634 | + 'cache map key: '.$textHash.', '. |
|
635 | + 'value type: '.gettype($matches).')' |
|
638 | 636 | ); |
639 | 637 | } |
640 | 638 | } else { |
641 | 639 | $key = 'wikibase.quality.constraints.regex.cache.miss'; |
642 | - $this->dataFactory->increment( $key ); |
|
643 | - return $this->matchesRegularExpressionWithSparql( $text, $regex ); |
|
640 | + $this->dataFactory->increment($key); |
|
641 | + return $this->matchesRegularExpressionWithSparql($text, $regex); |
|
644 | 642 | } |
645 | 643 | } |
646 | 644 | |
647 | - private function serializeConstraintParameterException( ConstraintParameterException $cpe ) { |
|
645 | + private function serializeConstraintParameterException(ConstraintParameterException $cpe) { |
|
648 | 646 | return [ |
649 | 647 | 'type' => ConstraintParameterException::class, |
650 | - 'violationMessage' => $this->violationMessageSerializer->serialize( $cpe->getViolationMessage() ), |
|
648 | + 'violationMessage' => $this->violationMessageSerializer->serialize($cpe->getViolationMessage()), |
|
651 | 649 | ]; |
652 | 650 | } |
653 | 651 | |
654 | - private function deserializeConstraintParameterException( array $serialization ) { |
|
652 | + private function deserializeConstraintParameterException(array $serialization) { |
|
655 | 653 | $message = $this->violationMessageDeserializer->deserialize( |
656 | 654 | $serialization['violationMessage'] |
657 | 655 | ); |
658 | - return new ConstraintParameterException( $message ); |
|
656 | + return new ConstraintParameterException($message); |
|
659 | 657 | } |
660 | 658 | |
661 | 659 | /** |
@@ -669,25 +667,25 @@ discard block |
||
669 | 667 | * @throws SparqlHelperException if the query times out or some other error occurs |
670 | 668 | * @throws ConstraintParameterException if the $regex is invalid |
671 | 669 | */ |
672 | - public function matchesRegularExpressionWithSparql( $text, $regex ) { |
|
673 | - $textStringLiteral = $this->stringLiteral( $text ); |
|
674 | - $regexStringLiteral = $this->stringLiteral( '^(?:' . $regex . ')$' ); |
|
670 | + public function matchesRegularExpressionWithSparql($text, $regex) { |
|
671 | + $textStringLiteral = $this->stringLiteral($text); |
|
672 | + $regexStringLiteral = $this->stringLiteral('^(?:'.$regex.')$'); |
|
675 | 673 | |
676 | 674 | $query = <<<EOF |
677 | 675 | SELECT (REGEX($textStringLiteral, $regexStringLiteral) AS ?matches) {} |
678 | 676 | EOF; |
679 | 677 | |
680 | - $result = $this->runQuery( $query, false ); |
|
678 | + $result = $this->runQuery($query, false); |
|
681 | 679 | |
682 | 680 | $vars = $result->getArray()['results']['bindings'][0]; |
683 | - if ( array_key_exists( 'matches', $vars ) ) { |
|
681 | + if (array_key_exists('matches', $vars)) { |
|
684 | 682 | // true or false ⇒ regex okay, text matches or not |
685 | 683 | return $vars['matches']['value'] === 'true'; |
686 | 684 | } else { |
687 | 685 | // empty result: regex broken |
688 | 686 | throw new ConstraintParameterException( |
689 | - ( new ViolationMessage( 'wbqc-violation-message-parameter-regex' ) ) |
|
690 | - ->withInlineCode( $regex, Role::CONSTRAINT_PARAMETER_VALUE ) |
|
687 | + (new ViolationMessage('wbqc-violation-message-parameter-regex')) |
|
688 | + ->withInlineCode($regex, Role::CONSTRAINT_PARAMETER_VALUE) |
|
691 | 689 | ); |
692 | 690 | } |
693 | 691 | } |
@@ -699,14 +697,14 @@ discard block |
||
699 | 697 | * |
700 | 698 | * @return boolean |
701 | 699 | */ |
702 | - public function isTimeout( $responseContent ) { |
|
703 | - $timeoutRegex = implode( '|', array_map( |
|
704 | - static function ( $fqn ) { |
|
705 | - return preg_quote( $fqn, '/' ); |
|
700 | + public function isTimeout($responseContent) { |
|
701 | + $timeoutRegex = implode('|', array_map( |
|
702 | + static function($fqn) { |
|
703 | + return preg_quote($fqn, '/'); |
|
706 | 704 | }, |
707 | 705 | $this->timeoutExceptionClasses |
708 | - ) ); |
|
709 | - return (bool)preg_match( '/' . $timeoutRegex . '/', $responseContent ); |
|
706 | + )); |
|
707 | + return (bool) preg_match('/'.$timeoutRegex.'/', $responseContent); |
|
710 | 708 | } |
711 | 709 | |
712 | 710 | /** |
@@ -718,17 +716,17 @@ discard block |
||
718 | 716 | * @return int|boolean the max-age (in seconds) |
719 | 717 | * or a plain boolean if no max-age can be determined |
720 | 718 | */ |
721 | - public function getCacheMaxAge( $responseHeaders ) { |
|
719 | + public function getCacheMaxAge($responseHeaders) { |
|
722 | 720 | if ( |
723 | - array_key_exists( 'x-cache-status', $responseHeaders ) && |
|
724 | - preg_match( '/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0] ) |
|
721 | + array_key_exists('x-cache-status', $responseHeaders) && |
|
722 | + preg_match('/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0]) |
|
725 | 723 | ) { |
726 | 724 | $maxage = []; |
727 | 725 | if ( |
728 | - array_key_exists( 'cache-control', $responseHeaders ) && |
|
729 | - preg_match( '/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage ) |
|
726 | + array_key_exists('cache-control', $responseHeaders) && |
|
727 | + preg_match('/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage) |
|
730 | 728 | ) { |
731 | - return intval( $maxage[1] ); |
|
729 | + return intval($maxage[1]); |
|
732 | 730 | } else { |
733 | 731 | return true; |
734 | 732 | } |
@@ -749,34 +747,34 @@ discard block |
||
749 | 747 | * or SparlHelper::EMPTY_RETRY_AFTER if there is an empty Retry-After |
750 | 748 | * or SparlHelper::INVALID_RETRY_AFTER if there is something wrong with the format |
751 | 749 | */ |
752 | - public function getThrottling( MWHttpRequest $request ) { |
|
753 | - $retryAfterValue = $request->getResponseHeader( 'Retry-After' ); |
|
754 | - if ( $retryAfterValue === null ) { |
|
750 | + public function getThrottling(MWHttpRequest $request) { |
|
751 | + $retryAfterValue = $request->getResponseHeader('Retry-After'); |
|
752 | + if ($retryAfterValue === null) { |
|
755 | 753 | return self::NO_RETRY_AFTER; |
756 | 754 | } |
757 | 755 | |
758 | - $trimmedRetryAfterValue = trim( $retryAfterValue ); |
|
759 | - if ( empty( $trimmedRetryAfterValue ) ) { |
|
756 | + $trimmedRetryAfterValue = trim($retryAfterValue); |
|
757 | + if (empty($trimmedRetryAfterValue)) { |
|
760 | 758 | return self::EMPTY_RETRY_AFTER; |
761 | 759 | } |
762 | 760 | |
763 | - if ( is_numeric( $trimmedRetryAfterValue ) ) { |
|
764 | - $delaySeconds = (int)$trimmedRetryAfterValue; |
|
765 | - if ( $delaySeconds >= 0 ) { |
|
766 | - return $this->getTimestampInFuture( new DateInterval( 'PT' . $delaySeconds . 'S' ) ); |
|
761 | + if (is_numeric($trimmedRetryAfterValue)) { |
|
762 | + $delaySeconds = (int) $trimmedRetryAfterValue; |
|
763 | + if ($delaySeconds >= 0) { |
|
764 | + return $this->getTimestampInFuture(new DateInterval('PT'.$delaySeconds.'S')); |
|
767 | 765 | } |
768 | 766 | } else { |
769 | - $return = strtotime( $trimmedRetryAfterValue ); |
|
770 | - if ( !empty( $return ) ) { |
|
771 | - return new ConvertibleTimestamp( $return ); |
|
767 | + $return = strtotime($trimmedRetryAfterValue); |
|
768 | + if (!empty($return)) { |
|
769 | + return new ConvertibleTimestamp($return); |
|
772 | 770 | } |
773 | 771 | } |
774 | 772 | return self::INVALID_RETRY_AFTER; |
775 | 773 | } |
776 | 774 | |
777 | - private function getTimestampInFuture( DateInterval $delta ) { |
|
775 | + private function getTimestampInFuture(DateInterval $delta) { |
|
778 | 776 | $now = new ConvertibleTimestamp(); |
779 | - return new ConvertibleTimestamp( $now->timestamp->add( $delta ) ); |
|
777 | + return new ConvertibleTimestamp($now->timestamp->add($delta)); |
|
780 | 778 | } |
781 | 779 | |
782 | 780 | /** |
@@ -790,65 +788,64 @@ discard block |
||
790 | 788 | * |
791 | 789 | * @throws SparqlHelperException if the query times out or some other error occurs |
792 | 790 | */ |
793 | - public function runQuery( $query, $needsPrefixes = true ) { |
|
791 | + public function runQuery($query, $needsPrefixes = true) { |
|
794 | 792 | |
795 | - if ( $this->throttlingLock->isLocked( self::EXPIRY_LOCK_ID ) ) { |
|
796 | - $this->dataFactory->increment( 'wikibase.quality.constraints.sparql.throttling' ); |
|
793 | + if ($this->throttlingLock->isLocked(self::EXPIRY_LOCK_ID)) { |
|
794 | + $this->dataFactory->increment('wikibase.quality.constraints.sparql.throttling'); |
|
797 | 795 | throw new TooManySparqlRequestsException(); |
798 | 796 | } |
799 | 797 | |
800 | - if ( $this->sparqlHasWikibaseSupport ) { |
|
798 | + if ($this->sparqlHasWikibaseSupport) { |
|
801 | 799 | $needsPrefixes = false; |
802 | 800 | } |
803 | 801 | |
804 | - if ( $needsPrefixes ) { |
|
805 | - $query = $this->prefixes . $query; |
|
802 | + if ($needsPrefixes) { |
|
803 | + $query = $this->prefixes.$query; |
|
806 | 804 | } |
807 | - $query = "#wbqc\n" . $query; |
|
805 | + $query = "#wbqc\n".$query; |
|
808 | 806 | |
809 | - $url = $this->endpoint . '?' . http_build_query( |
|
807 | + $url = $this->endpoint.'?'.http_build_query( |
|
810 | 808 | [ |
811 | 809 | 'query' => $query, |
812 | 810 | 'format' => 'json', |
813 | 811 | 'maxQueryTimeMillis' => $this->maxQueryTimeMillis, |
814 | 812 | ], |
815 | - '', ini_get( 'arg_separator.output' ), |
|
813 | + '', ini_get('arg_separator.output'), |
|
816 | 814 | // encode spaces with %20, not + |
817 | 815 | PHP_QUERY_RFC3986 |
818 | 816 | ); |
819 | 817 | |
820 | 818 | $options = [ |
821 | 819 | 'method' => 'GET', |
822 | - 'timeout' => (int)round( ( $this->maxQueryTimeMillis + 1000 ) / 1000 ), |
|
820 | + 'timeout' => (int) round(($this->maxQueryTimeMillis + 1000) / 1000), |
|
823 | 821 | 'connectTimeout' => 'default', |
824 | 822 | 'userAgent' => $this->defaultUserAgent, |
825 | 823 | ]; |
826 | - $request = $this->requestFactory->create( $url, $options, __METHOD__ ); |
|
827 | - $startTime = microtime( true ); |
|
824 | + $request = $this->requestFactory->create($url, $options, __METHOD__); |
|
825 | + $startTime = microtime(true); |
|
828 | 826 | $requestStatus = $request->execute(); |
829 | - $endTime = microtime( true ); |
|
827 | + $endTime = microtime(true); |
|
830 | 828 | $this->dataFactory->timing( |
831 | 829 | 'wikibase.quality.constraints.sparql.timing', |
832 | - ( $endTime - $startTime ) * 1000 |
|
830 | + ($endTime - $startTime) * 1000 |
|
833 | 831 | ); |
834 | 832 | |
835 | - $this->guardAgainstTooManyRequestsError( $request ); |
|
833 | + $this->guardAgainstTooManyRequestsError($request); |
|
836 | 834 | |
837 | - $maxAge = $this->getCacheMaxAge( $request->getResponseHeaders() ); |
|
838 | - if ( $maxAge ) { |
|
839 | - $this->dataFactory->increment( 'wikibase.quality.constraints.sparql.cached' ); |
|
835 | + $maxAge = $this->getCacheMaxAge($request->getResponseHeaders()); |
|
836 | + if ($maxAge) { |
|
837 | + $this->dataFactory->increment('wikibase.quality.constraints.sparql.cached'); |
|
840 | 838 | } |
841 | 839 | |
842 | - if ( $requestStatus->isOK() ) { |
|
840 | + if ($requestStatus->isOK()) { |
|
843 | 841 | $json = $request->getContent(); |
844 | - $jsonStatus = FormatJson::parse( $json, FormatJson::FORCE_ASSOC ); |
|
845 | - if ( $jsonStatus->isOK() ) { |
|
842 | + $jsonStatus = FormatJson::parse($json, FormatJson::FORCE_ASSOC); |
|
843 | + if ($jsonStatus->isOK()) { |
|
846 | 844 | return new CachedQueryResults( |
847 | 845 | $jsonStatus->getValue(), |
848 | 846 | Metadata::ofCachingMetadata( |
849 | 847 | $maxAge ? |
850 | - CachingMetadata::ofMaximumAgeInSeconds( $maxAge ) : |
|
851 | - CachingMetadata::fresh() |
|
848 | + CachingMetadata::ofMaximumAgeInSeconds($maxAge) : CachingMetadata::fresh() |
|
852 | 849 | ) |
853 | 850 | ); |
854 | 851 | } else { |
@@ -865,9 +862,9 @@ discard block |
||
865 | 862 | // fall through to general error handling |
866 | 863 | } |
867 | 864 | |
868 | - $this->dataFactory->increment( 'wikibase.quality.constraints.sparql.error' ); |
|
865 | + $this->dataFactory->increment('wikibase.quality.constraints.sparql.error'); |
|
869 | 866 | |
870 | - if ( $this->isTimeout( $request->getContent() ) ) { |
|
867 | + if ($this->isTimeout($request->getContent())) { |
|
871 | 868 | $this->dataFactory->increment( |
872 | 869 | 'wikibase.quality.constraints.sparql.error.timeout' |
873 | 870 | ); |
@@ -882,29 +879,29 @@ discard block |
||
882 | 879 | * @param MWHttpRequest $request |
883 | 880 | * @throws TooManySparqlRequestsException |
884 | 881 | */ |
885 | - private function guardAgainstTooManyRequestsError( MWHttpRequest $request ): void { |
|
886 | - if ( $request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS ) { |
|
882 | + private function guardAgainstTooManyRequestsError(MWHttpRequest $request): void { |
|
883 | + if ($request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS) { |
|
887 | 884 | return; |
888 | 885 | } |
889 | 886 | |
890 | 887 | $fallbackBlockDuration = $this->sparqlThrottlingFallbackDuration; |
891 | 888 | |
892 | - if ( $fallbackBlockDuration < 0 ) { |
|
893 | - throw new InvalidArgumentException( 'Fallback duration must be positive int but is: ' . |
|
894 | - $fallbackBlockDuration ); |
|
889 | + if ($fallbackBlockDuration < 0) { |
|
890 | + throw new InvalidArgumentException('Fallback duration must be positive int but is: '. |
|
891 | + $fallbackBlockDuration); |
|
895 | 892 | } |
896 | 893 | |
897 | - $this->dataFactory->increment( 'wikibase.quality.constraints.sparql.throttling' ); |
|
898 | - $throttlingUntil = $this->getThrottling( $request ); |
|
899 | - if ( !( $throttlingUntil instanceof ConvertibleTimestamp ) ) { |
|
900 | - $this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid( $request ); |
|
894 | + $this->dataFactory->increment('wikibase.quality.constraints.sparql.throttling'); |
|
895 | + $throttlingUntil = $this->getThrottling($request); |
|
896 | + if (!($throttlingUntil instanceof ConvertibleTimestamp)) { |
|
897 | + $this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid($request); |
|
901 | 898 | $this->throttlingLock->lock( |
902 | 899 | self::EXPIRY_LOCK_ID, |
903 | - $this->getTimestampInFuture( new DateInterval( 'PT' . $fallbackBlockDuration . 'S' ) ) |
|
900 | + $this->getTimestampInFuture(new DateInterval('PT'.$fallbackBlockDuration.'S')) |
|
904 | 901 | ); |
905 | 902 | } else { |
906 | - $this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent( $throttlingUntil, $request ); |
|
907 | - $this->throttlingLock->lock( self::EXPIRY_LOCK_ID, $throttlingUntil ); |
|
903 | + $this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent($throttlingUntil, $request); |
|
904 | + $this->throttlingLock->lock(self::EXPIRY_LOCK_ID, $throttlingUntil); |
|
908 | 905 | } |
909 | 906 | throw new TooManySparqlRequestsException(); |
910 | 907 | } |