Completed
Push — master ( 8dbc5b...7c5a90 )
by
unknown
01:10 queued 26s
created
src/ConstraintCheck/Helper/DummySparqlHelper.php 1 patch
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare( strict_types = 1 );
3
+declare(strict_types=1);
4 4
 
5 5
 namespace WikibaseQuality\ConstraintReport\ConstraintCheck\Helper;
6 6
 
@@ -28,15 +28,15 @@  discard block
 block discarded – undo
28 28
 		// no parent::__construct() call
29 29
 	}
30 30
 
31
-	public function hasType( EntityId $id, array $classes ): CachedBool {
32
-		throw new LogicException( 'methods of this class should never be called' );
31
+	public function hasType(EntityId $id, array $classes): CachedBool {
32
+		throw new LogicException('methods of this class should never be called');
33 33
 	}
34 34
 
35 35
 	public function findEntitiesWithSameStatement(
36 36
 		Statement $statement,
37 37
 		array $separators
38 38
 	): CachedEntityIds {
39
-		throw new LogicException( 'methods of this class should never be called' );
39
+		throw new LogicException('methods of this class should never be called');
40 40
 	}
41 41
 
42 42
 	public function findEntitiesWithSameQualifierOrReference(
@@ -45,15 +45,15 @@  discard block
 block discarded – undo
45 45
 		string $type,
46 46
 		bool $ignoreDeprecatedStatements
47 47
 	): CachedEntityIds {
48
-		throw new LogicException( 'methods of this class should never be called' );
48
+		throw new LogicException('methods of this class should never be called');
49 49
 	}
50 50
 
51
-	public function matchesRegularExpression( string $text, string $regex ): bool {
52
-		throw new LogicException( 'methods of this class should never be called' );
51
+	public function matchesRegularExpression(string $text, string $regex): bool {
52
+		throw new LogicException('methods of this class should never be called');
53 53
 	}
54 54
 
55
-	public function runQuery( string $query, string $endpoint, bool $needsPrefixes = true ): CachedQueryResults {
56
-		throw new LogicException( 'methods of this class should never be called' );
55
+	public function runQuery(string $query, string $endpoint, bool $needsPrefixes = true): CachedQueryResults {
56
+		throw new LogicException('methods of this class should never be called');
57 57
 	}
58 58
 
59 59
 }
Please login to merge, or discard this patch.
src/ConstraintCheck/Helper/SparqlHelper.php 1 patch
Spacing   +191 added lines, -194 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare( strict_types = 1 );
3
+declare(strict_types=1);
4 4
 
5 5
 namespace WikibaseQuality\ConstraintReport\ConstraintCheck\Helper;
6 6
 
@@ -148,94 +148,94 @@  discard block
 block discarded – undo
148 148
 		$this->defaultUserAgent = $defaultUserAgent;
149 149
 		$this->requestFactory = $requestFactory;
150 150
 		$this->entityPrefixes = [];
151
-		foreach ( $rdfVocabulary->entityNamespaceNames as $namespaceName ) {
152
-			$this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI( $namespaceName );
151
+		foreach ($rdfVocabulary->entityNamespaceNames as $namespaceName) {
152
+			$this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI($namespaceName);
153 153
 		}
154 154
 
155
-		$this->primaryEndpoint = $config->get( 'WBQualityConstraintsSparqlEndpoint' );
156
-		$this->additionalEndpoints = $config->get( 'WBQualityConstraintsAdditionalSparqlEndpoints' ) ?: [];
157
-		$this->maxQueryTimeMillis = $config->get( 'WBQualityConstraintsSparqlMaxMillis' );
158
-		$this->subclassOfId = new NumericPropertyId( $config->get( 'WBQualityConstraintsSubclassOfId' ) );
159
-		$this->cacheMapSize = $config->get( 'WBQualityConstraintsFormatCacheMapSize' );
155
+		$this->primaryEndpoint = $config->get('WBQualityConstraintsSparqlEndpoint');
156
+		$this->additionalEndpoints = $config->get('WBQualityConstraintsAdditionalSparqlEndpoints') ?: [];
157
+		$this->maxQueryTimeMillis = $config->get('WBQualityConstraintsSparqlMaxMillis');
158
+		$this->subclassOfId = new NumericPropertyId($config->get('WBQualityConstraintsSubclassOfId'));
159
+		$this->cacheMapSize = $config->get('WBQualityConstraintsFormatCacheMapSize');
160 160
 		$this->timeoutExceptionClasses = $config->get(
161 161
 			'WBQualityConstraintsSparqlTimeoutExceptionClasses'
162 162
 		);
163 163
 		$this->sparqlHasWikibaseSupport = $config->get(
164 164
 			'WBQualityConstraintsSparqlHasWikibaseSupport'
165 165
 		);
166
-		$this->sparqlThrottlingFallbackDuration = (int)$config->get(
166
+		$this->sparqlThrottlingFallbackDuration = (int) $config->get(
167 167
 			'WBQualityConstraintsSparqlThrottlingFallbackDuration'
168 168
 		);
169 169
 
170
-		$this->prefixes = $this->getQueryPrefixes( $rdfVocabulary );
170
+		$this->prefixes = $this->getQueryPrefixes($rdfVocabulary);
171 171
 	}
172 172
 
173
-	private function getQueryPrefixes( RdfVocabulary $rdfVocabulary ): string {
173
+	private function getQueryPrefixes(RdfVocabulary $rdfVocabulary): string {
174 174
 		// TODO: it would probably be smarter that RdfVocabulary exposed these prefixes somehow
175 175
 		$prefixes = '';
176
-		foreach ( $rdfVocabulary->entityNamespaceNames as $sourceName => $namespaceName ) {
176
+		foreach ($rdfVocabulary->entityNamespaceNames as $sourceName => $namespaceName) {
177 177
 			$prefixes .= <<<END
178
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
178
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
179 179
 END;
180 180
 		}
181 181
 
182
-		$itemSourceName = $rdfVocabulary->getEntityRepositoryName( new ItemId( 'Q1' ) );
182
+		$itemSourceName = $rdfVocabulary->getEntityRepositoryName(new ItemId('Q1'));
183 183
 		$namespaceName = $rdfVocabulary->statementNamespaceNames[$itemSourceName][RdfVocabulary::NS_STATEMENT];
184 184
 		$prefixes .= <<<END
185
-PREFIX wds: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
185
+PREFIX wds: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
186 186
 END;
187 187
 		$namespaceName = $rdfVocabulary->statementNamespaceNames[$itemSourceName][RdfVocabulary::NS_VALUE];
188 188
 		$prefixes .= <<<END
189
-PREFIX wdv: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
189
+PREFIX wdv: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
190 190
 END;
191 191
 
192
-		foreach ( $rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces ) {
192
+		foreach ($rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces) {
193 193
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_DIRECT_CLAIM];
194 194
 			$prefixes .= <<<END
195
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
195
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
196 196
 END;
197 197
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM];
198 198
 			$prefixes .= <<<END
199
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
199
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
200 200
 END;
201 201
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM_STATEMENT];
202 202
 			$prefixes .= <<<END
203
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
203
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
204 204
 END;
205 205
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER];
206 206
 			$prefixes .= <<<END
207
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
207
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
208 208
 END;
209 209
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER_VALUE];
210 210
 			$prefixes .= <<<END
211
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
211
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
212 212
 END;
213 213
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE];
214 214
 			$prefixes .= <<<END
215
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
215
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
216 216
 END;
217 217
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE_VALUE];
218 218
 			$prefixes .= <<<END
219
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
219
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
220 220
 END;
221 221
 		}
222 222
 		$namespaceName = RdfVocabulary::NS_ONTOLOGY;
223 223
 		$prefixes .= <<<END
224
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
224
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
225 225
 END;
226 226
 		return $prefixes;
227 227
 	}
228 228
 
229 229
 	/** Return a SPARQL term like `wd:Q123` for the given ID. */
230
-	private function wd( EntityId $id ): string {
231
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
230
+	private function wd(EntityId $id): string {
231
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
232 232
 		$prefix = $this->rdfVocabulary->entityNamespaceNames[$repository];
233 233
 		return "$prefix:{$id->getSerialization()}";
234 234
 	}
235 235
 
236 236
 	/** Return a SPARQL term like `wdt:P123` for the given ID. */
237
-	private function wdt( PropertyId $id ): string {
238
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
237
+	private function wdt(PropertyId $id): string {
238
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
239 239
 		$prefix = $this->rdfVocabulary->propertyNamespaceNames[$repository][RdfVocabulary::NSP_DIRECT_CLAIM];
240 240
 		return "$prefix:{$id->getSerialization()}";
241 241
 	}
@@ -247,43 +247,42 @@  discard block
 block discarded – undo
247 247
 	 * @return CachedBool
248 248
 	 * @throws SparqlHelperException if the query times out or some other error occurs
249 249
 	 */
250
-	public function hasType( EntityId $id, array $classes ): CachedBool {
250
+	public function hasType(EntityId $id, array $classes): CachedBool {
251 251
 		// TODO hint:gearing is a workaround for T168973 and can hopefully be removed eventually
252 252
 		$gearingHint = $this->sparqlHasWikibaseSupport ?
253
-			' hint:Prior hint:gearing "forward".' :
254
-			'';
253
+			' hint:Prior hint:gearing "forward".' : '';
255 254
 
256 255
 		$metadatas = [];
257 256
 
258
-		foreach ( array_chunk( $classes, 20 ) as $classesChunk ) {
259
-			$classesValues = implode( ' ', array_map(
260
-				function ( string $class ) {
261
-					return $this->wd( new ItemId( $class ) );
257
+		foreach (array_chunk($classes, 20) as $classesChunk) {
258
+			$classesValues = implode(' ', array_map(
259
+				function(string $class) {
260
+					return $this->wd(new ItemId($class));
262 261
 				},
263 262
 				$classesChunk
264
-			) );
263
+			));
265 264
 
266 265
 			$query = <<<EOF
267 266
 ASK {
268
-  BIND({$this->wd( $id )} AS ?item)
267
+  BIND({$this->wd($id)} AS ?item)
269 268
   VALUES ?class { $classesValues }
270
-  ?item {$this->wdt( $this->subclassOfId )}* ?class.$gearingHint
269
+  ?item {$this->wdt($this->subclassOfId)}* ?class.$gearingHint
271 270
 }
272 271
 EOF;
273 272
 
274
-			$result = $this->runQuery( $query, $this->primaryEndpoint );
273
+			$result = $this->runQuery($query, $this->primaryEndpoint);
275 274
 			$metadatas[] = $result->getMetadata();
276
-			if ( $result->getArray()['boolean'] ) {
275
+			if ($result->getArray()['boolean']) {
277 276
 				return new CachedBool(
278 277
 					true,
279
-					Metadata::merge( $metadatas )
278
+					Metadata::merge($metadatas)
280 279
 				);
281 280
 			}
282 281
 		}
283 282
 
284 283
 		return new CachedBool(
285 284
 			false,
286
-			Metadata::merge( $metadatas )
285
+			Metadata::merge($metadatas)
287 286
 		);
288 287
 	}
289 288
 
@@ -291,7 +290,7 @@  discard block
 block discarded – undo
291 290
 	 * Helper function used by findEntitiesWithSameStatement to filter
292 291
 	 * out entities with different qualifiers or no qualifier value.
293 292
 	 */
294
-	private function nestedSeparatorFilter( PropertyId $separator ): string {
293
+	private function nestedSeparatorFilter(PropertyId $separator): string {
295 294
 		$filter = <<<EOF
296 295
   MINUS {
297 296
     ?statement pq:$separator ?qualifier.
@@ -328,14 +327,14 @@  discard block
 block discarded – undo
328 327
 	 * @return CachedEntityIds
329 328
 	 * @throws SparqlHelperException if the query times out or some other error occurs
330 329
 	 */
331
-	public function findEntitiesWithSameStatement( Statement $statement, array $separators ): CachedEntityIds {
330
+	public function findEntitiesWithSameStatement(Statement $statement, array $separators): CachedEntityIds {
332 331
 		$pid = $statement->getPropertyId()->getSerialization();
333 332
 		$guid = $statement->getGuid();
334 333
 		'@phan-var string $guid'; // statement must have a non-null GUID
335
-		$guidForRdf = str_replace( '$', '-', $guid );
334
+		$guidForRdf = str_replace('$', '-', $guid);
336 335
 
337
-		$separatorFilters = array_map( [ $this, 'nestedSeparatorFilter' ], $separators );
338
-		$finalSeparatorFilter = implode( "\n", $separatorFilters );
336
+		$separatorFilters = array_map([$this, 'nestedSeparatorFilter'], $separators);
337
+		$finalSeparatorFilter = implode("\n", $separatorFilters);
339 338
 
340 339
 		$query = <<<EOF
341 340
 SELECT DISTINCT ?otherEntity WHERE {
@@ -353,12 +352,12 @@  discard block
 block discarded – undo
353 352
 LIMIT 10
354 353
 EOF;
355 354
 
356
-		$results = [ $this->runQuery( $query, $this->primaryEndpoint ) ];
357
-		foreach ( $this->additionalEndpoints as $endpoint ) {
358
-			$results[] = $this->runQuery( $query, $endpoint );
355
+		$results = [$this->runQuery($query, $this->primaryEndpoint)];
356
+		foreach ($this->additionalEndpoints as $endpoint) {
357
+			$results[] = $this->runQuery($query, $endpoint);
359 358
 		}
360 359
 
361
-		return $this->getOtherEntities( $results );
360
+		return $this->getOtherEntities($results);
362 361
 	}
363 362
 
364 363
 	/**
@@ -383,16 +382,15 @@  discard block
 block discarded – undo
383 382
 		$dataType = $this->propertyDataTypeLookup->getDataTypeIdForProperty(
384 383
 			$snak->getPropertyId()
385 384
 		);
386
-		[ $value, $isFullValue ] = $this->getRdfLiteral( $dataType, $dataValue );
387
-		if ( $isFullValue ) {
385
+		[$value, $isFullValue] = $this->getRdfLiteral($dataType, $dataValue);
386
+		if ($isFullValue) {
388 387
 			$prefix .= 'v';
389 388
 		}
390 389
 		$path = $type === Context::TYPE_QUALIFIER ?
391
-			"$prefix:$pid" :
392
-			"prov:wasDerivedFrom/$prefix:$pid";
390
+			"$prefix:$pid" : "prov:wasDerivedFrom/$prefix:$pid";
393 391
 
394 392
 		$deprecatedFilter = '';
395
-		if ( $ignoreDeprecatedStatements ) {
393
+		if ($ignoreDeprecatedStatements) {
396 394
 			$deprecatedFilter = <<< EOF
397 395
   MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. }
398 396
 EOF;
@@ -412,19 +410,19 @@  discard block
 block discarded – undo
412 410
 LIMIT 10
413 411
 EOF;
414 412
 
415
-		$results = [ $this->runQuery( $query, $this->primaryEndpoint ) ];
416
-		foreach ( $this->additionalEndpoints as $endpoint ) {
417
-			$results[] = $this->runQuery( $query, $endpoint );
413
+		$results = [$this->runQuery($query, $this->primaryEndpoint)];
414
+		foreach ($this->additionalEndpoints as $endpoint) {
415
+			$results[] = $this->runQuery($query, $endpoint);
418 416
 		}
419 417
 
420
-		return $this->getOtherEntities( $results );
418
+		return $this->getOtherEntities($results);
421 419
 	}
422 420
 
423 421
 	/**
424 422
 	 * Return SPARQL code for a string literal with $text as content.
425 423
 	 */
426
-	private function stringLiteral( string $text ): string {
427
-		return '"' . strtr( $text, [ '"' => '\\"', '\\' => '\\\\' ] ) . '"';
424
+	private function stringLiteral(string $text): string {
425
+		return '"'.strtr($text, ['"' => '\\"', '\\' => '\\\\']).'"';
428 426
 	}
429 427
 
430 428
 	/**
@@ -434,26 +432,26 @@  discard block
 block discarded – undo
434 432
 	 *
435 433
 	 * @return CachedEntityIds
436 434
 	 */
437
-	private function getOtherEntities( array $results ): CachedEntityIds {
435
+	private function getOtherEntities(array $results): CachedEntityIds {
438 436
 		$allResultBindings = [];
439 437
 		$metadatas = [];
440 438
 
441
-		foreach ( $results as $result ) {
439
+		foreach ($results as $result) {
442 440
 			$metadatas[] = $result->getMetadata();
443
-			$allResultBindings = array_merge( $allResultBindings, $result->getArray()['results']['bindings'] );
441
+			$allResultBindings = array_merge($allResultBindings, $result->getArray()['results']['bindings']);
444 442
 		}
445 443
 
446 444
 		$entityIds = array_map(
447
-			function ( $resultBindings ) {
445
+			function($resultBindings) {
448 446
 				$entityIRI = $resultBindings['otherEntity']['value'];
449
-				foreach ( $this->entityPrefixes as $entityPrefix ) {
450
-					$entityPrefixLength = strlen( $entityPrefix );
451
-					if ( substr( $entityIRI, 0, $entityPrefixLength ) === $entityPrefix ) {
447
+				foreach ($this->entityPrefixes as $entityPrefix) {
448
+					$entityPrefixLength = strlen($entityPrefix);
449
+					if (substr($entityIRI, 0, $entityPrefixLength) === $entityPrefix) {
452 450
 						try {
453 451
 							return $this->entityIdParser->parse(
454
-								substr( $entityIRI, $entityPrefixLength )
452
+								substr($entityIRI, $entityPrefixLength)
455 453
 							);
456
-						} catch ( EntityIdParsingException $e ) {
454
+						} catch (EntityIdParsingException $e) {
457 455
 							// fall through
458 456
 						}
459 457
 					}
@@ -467,8 +465,8 @@  discard block
 block discarded – undo
467 465
 		);
468 466
 
469 467
 		return new CachedEntityIds(
470
-			array_values( array_filter( array_unique( $entityIds ) ) ),
471
-			Metadata::merge( $metadatas )
468
+			array_values(array_filter(array_unique($entityIds))),
469
+			Metadata::merge($metadatas)
472 470
 		);
473 471
 	}
474 472
 
@@ -479,50 +477,50 @@  discard block
 block discarded – undo
479 477
 	 * @return array the literal or IRI as a string in SPARQL syntax,
480 478
 	 * and a boolean indicating whether it refers to a full value node or not
481 479
 	 */
482
-	private function getRdfLiteral( string $dataType, DataValue $dataValue ): array {
483
-		switch ( $dataType ) {
480
+	private function getRdfLiteral(string $dataType, DataValue $dataValue): array {
481
+		switch ($dataType) {
484 482
 			case 'string':
485 483
 			case 'external-id':
486
-				return [ $this->stringLiteral( $dataValue->getValue() ), false ];
484
+				return [$this->stringLiteral($dataValue->getValue()), false];
487 485
 			case 'commonsMedia':
488
-				$url = $this->rdfVocabulary->getMediaFileURI( $dataValue->getValue() );
489
-				return [ '<' . $url . '>', false ];
486
+				$url = $this->rdfVocabulary->getMediaFileURI($dataValue->getValue());
487
+				return ['<'.$url.'>', false];
490 488
 			case 'geo-shape':
491
-				$url = $this->rdfVocabulary->getGeoShapeURI( $dataValue->getValue() );
492
-				return [ '<' . $url . '>', false ];
489
+				$url = $this->rdfVocabulary->getGeoShapeURI($dataValue->getValue());
490
+				return ['<'.$url.'>', false];
493 491
 			case 'tabular-data':
494
-				$url = $this->rdfVocabulary->getTabularDataURI( $dataValue->getValue() );
495
-				return [ '<' . $url . '>', false ];
492
+				$url = $this->rdfVocabulary->getTabularDataURI($dataValue->getValue());
493
+				return ['<'.$url.'>', false];
496 494
 			case 'url':
497 495
 				$url = $dataValue->getValue();
498
-				if ( !preg_match( '/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url ) ) {
496
+				if (!preg_match('/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url)) {
499 497
 					// not a valid URL for SPARQL (see SPARQL spec, production 139 IRIREF)
500 498
 					// such an URL should never reach us, so just throw
501
-					throw new InvalidArgumentException( 'invalid URL: ' . $url );
499
+					throw new InvalidArgumentException('invalid URL: '.$url);
502 500
 				}
503
-				return [ '<' . $url . '>', false ];
501
+				return ['<'.$url.'>', false];
504 502
 			case 'wikibase-item':
505 503
 			case 'wikibase-property':
506 504
 				/** @var EntityIdValue $dataValue */
507 505
 				'@phan-var EntityIdValue $dataValue';
508
-				return [ 'wd:' . $dataValue->getEntityId()->getSerialization(), false ];
506
+				return ['wd:'.$dataValue->getEntityId()->getSerialization(), false];
509 507
 			case 'monolingualtext':
510 508
 				/** @var MonolingualTextValue $dataValue */
511 509
 				'@phan-var MonolingualTextValue $dataValue';
512 510
 				$lang = $dataValue->getLanguageCode();
513
-				if ( !preg_match( '/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang ) ) {
511
+				if (!preg_match('/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang)) {
514 512
 					// not a valid language tag for SPARQL (see SPARQL spec, production 145 LANGTAG)
515 513
 					// such a language tag should never reach us, so just throw
516
-					throw new InvalidArgumentException( 'invalid language tag: ' . $lang );
514
+					throw new InvalidArgumentException('invalid language tag: '.$lang);
517 515
 				}
518
-				return [ $this->stringLiteral( $dataValue->getText() ) . '@' . $lang, false ];
516
+				return [$this->stringLiteral($dataValue->getText()).'@'.$lang, false];
519 517
 			case 'globe-coordinate':
520 518
 			case 'quantity':
521 519
 			case 'time':
522 520
 				// @phan-suppress-next-line PhanUndeclaredMethod
523
-				return [ 'wdv:' . $dataValue->getHash(), true ];
521
+				return ['wdv:'.$dataValue->getHash(), true];
524 522
 			default:
525
-				throw new InvalidArgumentException( 'unknown data type: ' . $dataType );
523
+				throw new InvalidArgumentException('unknown data type: '.$dataType);
526 524
 		}
527 525
 	}
528 526
 	// phpcs:enable
@@ -531,43 +529,43 @@  discard block
 block discarded – undo
531 529
 	 * @throws SparqlHelperException if the query times out or some other error occurs
532 530
 	 * @throws ConstraintParameterException if the $regex is invalid
533 531
 	 */
534
-	public function matchesRegularExpression( string $text, string $regex ): bool {
532
+	public function matchesRegularExpression(string $text, string $regex): bool {
535 533
 		// caching wrapper around matchesRegularExpressionWithSparql
536 534
 
537
-		$textHash = hash( 'sha256', $text );
535
+		$textHash = hash('sha256', $text);
538 536
 		$cacheKey = $this->cache->makeKey(
539 537
 			'WikibaseQualityConstraints', // extension
540 538
 			'regex', // action
541 539
 			'WDQS-Java', // regex flavor
542
-			hash( 'sha256', $regex )
540
+			hash('sha256', $regex)
543 541
 		);
544 542
 
545 543
 		$cacheMapArray = $this->cache->getWithSetCallback(
546 544
 			$cacheKey,
547 545
 			WANObjectCache::TTL_DAY,
548
-			function ( $cacheMapArray ) use ( $text, $regex, $textHash ) {
546
+			function($cacheMapArray) use ($text, $regex, $textHash) {
549 547
 				// Initialize the cache map if not set
550
-				if ( $cacheMapArray === false ) {
548
+				if ($cacheMapArray === false) {
551 549
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.init';
552
-					$this->dataFactory->increment( $key );
550
+					$this->dataFactory->increment($key);
553 551
 					return [];
554 552
 				}
555 553
 
556 554
 				$key = 'wikibase.quality.constraints.regex.cache.refresh';
557
-				$this->dataFactory->increment( $key );
558
-				$cacheMap = MapCacheLRU::newFromArray( $cacheMapArray, $this->cacheMapSize );
559
-				if ( $cacheMap->has( $textHash ) ) {
555
+				$this->dataFactory->increment($key);
556
+				$cacheMap = MapCacheLRU::newFromArray($cacheMapArray, $this->cacheMapSize);
557
+				if ($cacheMap->has($textHash)) {
560 558
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.hit';
561
-					$this->dataFactory->increment( $key );
562
-					$cacheMap->get( $textHash ); // ping cache
559
+					$this->dataFactory->increment($key);
560
+					$cacheMap->get($textHash); // ping cache
563 561
 				} else {
564 562
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.miss';
565
-					$this->dataFactory->increment( $key );
563
+					$this->dataFactory->increment($key);
566 564
 					try {
567
-						$matches = $this->matchesRegularExpressionWithSparql( $text, $regex );
568
-					} catch ( ConstraintParameterException $e ) {
569
-						$matches = $this->serializeConstraintParameterException( $e );
570
-					} catch ( SparqlHelperException $e ) {
565
+						$matches = $this->matchesRegularExpressionWithSparql($text, $regex);
566
+					} catch (ConstraintParameterException $e) {
567
+						$matches = $this->serializeConstraintParameterException($e);
568
+					} catch (SparqlHelperException $e) {
571 569
 						// don’t cache this
572 570
 						return $cacheMap->toArray();
573 571
 					}
@@ -591,42 +589,42 @@  discard block
 block discarded – undo
591 589
 			]
592 590
 		);
593 591
 
594
-		if ( isset( $cacheMapArray[$textHash] ) ) {
592
+		if (isset($cacheMapArray[$textHash])) {
595 593
 			$key = 'wikibase.quality.constraints.regex.cache.hit';
596
-			$this->dataFactory->increment( $key );
594
+			$this->dataFactory->increment($key);
597 595
 			$matches = $cacheMapArray[$textHash];
598
-			if ( is_bool( $matches ) ) {
596
+			if (is_bool($matches)) {
599 597
 				return $matches;
600
-			} elseif ( is_array( $matches ) &&
601
-				$matches['type'] == ConstraintParameterException::class ) {
602
-				throw $this->deserializeConstraintParameterException( $matches );
598
+			} elseif (is_array($matches) &&
599
+				$matches['type'] == ConstraintParameterException::class) {
600
+				throw $this->deserializeConstraintParameterException($matches);
603 601
 			} else {
604 602
 				throw new UnexpectedValueException(
605
-					'Value of unknown type in object cache (' .
606
-					'cache key: ' . $cacheKey . ', ' .
607
-					'cache map key: ' . $textHash . ', ' .
608
-					'value type: ' . get_debug_type( $matches ) . ')'
603
+					'Value of unknown type in object cache ('.
604
+					'cache key: '.$cacheKey.', '.
605
+					'cache map key: '.$textHash.', '.
606
+					'value type: '.get_debug_type($matches).')'
609 607
 				);
610 608
 			}
611 609
 		} else {
612 610
 			$key = 'wikibase.quality.constraints.regex.cache.miss';
613
-			$this->dataFactory->increment( $key );
614
-			return $this->matchesRegularExpressionWithSparql( $text, $regex );
611
+			$this->dataFactory->increment($key);
612
+			return $this->matchesRegularExpressionWithSparql($text, $regex);
615 613
 		}
616 614
 	}
617 615
 
618
-	private function serializeConstraintParameterException( ConstraintParameterException $cpe ): array {
616
+	private function serializeConstraintParameterException(ConstraintParameterException $cpe): array {
619 617
 		return [
620 618
 			'type' => ConstraintParameterException::class,
621
-			'violationMessage' => $this->violationMessageSerializer->serialize( $cpe->getViolationMessage() ),
619
+			'violationMessage' => $this->violationMessageSerializer->serialize($cpe->getViolationMessage()),
622 620
 		];
623 621
 	}
624 622
 
625
-	private function deserializeConstraintParameterException( array $serialization ): ConstraintParameterException {
623
+	private function deserializeConstraintParameterException(array $serialization): ConstraintParameterException {
626 624
 		$message = $this->violationMessageDeserializer->deserialize(
627 625
 			$serialization['violationMessage']
628 626
 		);
629
-		return new ConstraintParameterException( $message );
627
+		return new ConstraintParameterException($message);
630 628
 	}
631 629
 
632 630
 	/**
@@ -636,25 +634,25 @@  discard block
 block discarded – undo
636 634
 	 * @throws SparqlHelperException if the query times out or some other error occurs
637 635
 	 * @throws ConstraintParameterException if the $regex is invalid
638 636
 	 */
639
-	public function matchesRegularExpressionWithSparql( string $text, string $regex ): bool {
640
-		$textStringLiteral = $this->stringLiteral( $text );
641
-		$regexStringLiteral = $this->stringLiteral( '^(?:' . $regex . ')$' );
637
+	public function matchesRegularExpressionWithSparql(string $text, string $regex): bool {
638
+		$textStringLiteral = $this->stringLiteral($text);
639
+		$regexStringLiteral = $this->stringLiteral('^(?:'.$regex.')$');
642 640
 
643 641
 		$query = <<<EOF
644 642
 SELECT (REGEX($textStringLiteral, $regexStringLiteral) AS ?matches) {}
645 643
 EOF;
646 644
 
647
-		$result = $this->runQuery( $query, $this->primaryEndpoint, false );
645
+		$result = $this->runQuery($query, $this->primaryEndpoint, false);
648 646
 
649 647
 		$vars = $result->getArray()['results']['bindings'][0];
650
-		if ( array_key_exists( 'matches', $vars ) ) {
648
+		if (array_key_exists('matches', $vars)) {
651 649
 			// true or false ⇒ regex okay, text matches or not
652 650
 			return $vars['matches']['value'] === 'true';
653 651
 		} else {
654 652
 			// empty result: regex broken
655 653
 			throw new ConstraintParameterException(
656
-				( new ViolationMessage( 'wbqc-violation-message-parameter-regex' ) )
657
-					->withInlineCode( $regex, Role::CONSTRAINT_PARAMETER_VALUE )
654
+				(new ViolationMessage('wbqc-violation-message-parameter-regex'))
655
+					->withInlineCode($regex, Role::CONSTRAINT_PARAMETER_VALUE)
658 656
 			);
659 657
 		}
660 658
 	}
@@ -662,14 +660,14 @@  discard block
 block discarded – undo
662 660
 	/**
663 661
 	 * Check whether the text content of an error response indicates a query timeout.
664 662
 	 */
665
-	public function isTimeout( string $responseContent ): bool {
666
-		$timeoutRegex = implode( '|', array_map(
667
-			static function ( $fqn ) {
668
-				return preg_quote( $fqn, '/' );
663
+	public function isTimeout(string $responseContent): bool {
664
+		$timeoutRegex = implode('|', array_map(
665
+			static function($fqn) {
666
+				return preg_quote($fqn, '/');
669 667
 			},
670 668
 			$this->timeoutExceptionClasses
671
-		) );
672
-		return (bool)preg_match( '/' . $timeoutRegex . '/', $responseContent );
669
+		));
670
+		return (bool) preg_match('/'.$timeoutRegex.'/', $responseContent);
673 671
 	}
674 672
 
675 673
 	/**
@@ -681,17 +679,17 @@  discard block
 block discarded – undo
681 679
 	 * @return int|boolean the max-age (in seconds)
682 680
 	 * or a plain boolean if no max-age can be determined
683 681
 	 */
684
-	public function getCacheMaxAge( array $responseHeaders ) {
682
+	public function getCacheMaxAge(array $responseHeaders) {
685 683
 		if (
686
-			array_key_exists( 'x-cache-status', $responseHeaders ) &&
687
-			preg_match( '/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0] )
684
+			array_key_exists('x-cache-status', $responseHeaders) &&
685
+			preg_match('/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0])
688 686
 		) {
689 687
 			$maxage = [];
690 688
 			if (
691
-				array_key_exists( 'cache-control', $responseHeaders ) &&
692
-				preg_match( '/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage )
689
+				array_key_exists('cache-control', $responseHeaders) &&
690
+				preg_match('/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage)
693 691
 			) {
694
-				return intval( $maxage[1] );
692
+				return intval($maxage[1]);
695 693
 			} else {
696 694
 				return true;
697 695
 			}
@@ -712,34 +710,34 @@  discard block
 block discarded – undo
712 710
 	 * or SparlHelper::EMPTY_RETRY_AFTER if there is an empty Retry-After
713 711
 	 * or SparlHelper::INVALID_RETRY_AFTER if there is something wrong with the format
714 712
 	 */
715
-	public function getThrottling( MWHttpRequest $request ) {
716
-		$retryAfterValue = $request->getResponseHeader( 'Retry-After' );
717
-		if ( $retryAfterValue === null ) {
713
+	public function getThrottling(MWHttpRequest $request) {
714
+		$retryAfterValue = $request->getResponseHeader('Retry-After');
715
+		if ($retryAfterValue === null) {
718 716
 			return self::NO_RETRY_AFTER;
719 717
 		}
720 718
 
721
-		$trimmedRetryAfterValue = trim( $retryAfterValue );
722
-		if ( $trimmedRetryAfterValue === '' ) {
719
+		$trimmedRetryAfterValue = trim($retryAfterValue);
720
+		if ($trimmedRetryAfterValue === '') {
723 721
 			return self::EMPTY_RETRY_AFTER;
724 722
 		}
725 723
 
726
-		if ( is_numeric( $trimmedRetryAfterValue ) ) {
727
-			$delaySeconds = (int)$trimmedRetryAfterValue;
728
-			if ( $delaySeconds >= 0 ) {
729
-				return $this->getTimestampInFuture( new DateInterval( 'PT' . $delaySeconds . 'S' ) );
724
+		if (is_numeric($trimmedRetryAfterValue)) {
725
+			$delaySeconds = (int) $trimmedRetryAfterValue;
726
+			if ($delaySeconds >= 0) {
727
+				return $this->getTimestampInFuture(new DateInterval('PT'.$delaySeconds.'S'));
730 728
 			}
731 729
 		} else {
732
-			$return = strtotime( $trimmedRetryAfterValue );
733
-			if ( $return !== false ) {
734
-				return new ConvertibleTimestamp( $return );
730
+			$return = strtotime($trimmedRetryAfterValue);
731
+			if ($return !== false) {
732
+				return new ConvertibleTimestamp($return);
735 733
 			}
736 734
 		}
737 735
 		return self::INVALID_RETRY_AFTER;
738 736
 	}
739 737
 
740
-	private function getTimestampInFuture( DateInterval $delta ): ConvertibleTimestamp {
738
+	private function getTimestampInFuture(DateInterval $delta): ConvertibleTimestamp {
741 739
 		$now = new ConvertibleTimestamp();
742
-		return new ConvertibleTimestamp( $now->timestamp->add( $delta ) );
740
+		return new ConvertibleTimestamp($now->timestamp->add($delta));
743 741
 	}
744 742
 
745 743
 	/**
@@ -754,64 +752,63 @@  discard block
 block discarded – undo
754 752
 	 *
755 753
 	 * @throws SparqlHelperException if the query times out or some other error occurs
756 754
 	 */
757
-	protected function runQuery( string $query, string $endpoint, bool $needsPrefixes = true ): CachedQueryResults {
758
-		if ( $this->throttlingLock->isLocked( self::EXPIRY_LOCK_ID ) ) {
759
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.throttling' );
755
+	protected function runQuery(string $query, string $endpoint, bool $needsPrefixes = true): CachedQueryResults {
756
+		if ($this->throttlingLock->isLocked(self::EXPIRY_LOCK_ID)) {
757
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.throttling');
760 758
 			throw new TooManySparqlRequestsException();
761 759
 		}
762 760
 
763
-		if ( $this->sparqlHasWikibaseSupport ) {
761
+		if ($this->sparqlHasWikibaseSupport) {
764 762
 			$needsPrefixes = false;
765 763
 		}
766 764
 
767
-		if ( $needsPrefixes ) {
768
-			$query = $this->prefixes . $query;
765
+		if ($needsPrefixes) {
766
+			$query = $this->prefixes.$query;
769 767
 		}
770
-		$query = "#wbqc\n" . $query;
768
+		$query = "#wbqc\n".$query;
771 769
 
772
-		$url = $endpoint . '?' . http_build_query(
770
+		$url = $endpoint.'?'.http_build_query(
773 771
 			[
774 772
 				'query' => $query,
775 773
 				'format' => 'json',
776 774
 				'maxQueryTimeMillis' => $this->maxQueryTimeMillis,
777 775
 			],
778
-			'', ini_get( 'arg_separator.output' ),
776
+			'', ini_get('arg_separator.output'),
779 777
 			// encode spaces with %20, not +
780 778
 			PHP_QUERY_RFC3986
781 779
 		);
782 780
 
783 781
 		$options = [
784 782
 			'method' => 'GET',
785
-			'timeout' => (int)round( ( $this->maxQueryTimeMillis + 1000 ) / 1000 ),
783
+			'timeout' => (int) round(($this->maxQueryTimeMillis + 1000) / 1000),
786 784
 			'connectTimeout' => 'default',
787 785
 			'userAgent' => $this->defaultUserAgent,
788 786
 		];
789
-		$request = $this->requestFactory->create( $url, $options, __METHOD__ );
790
-		$startTime = microtime( true );
787
+		$request = $this->requestFactory->create($url, $options, __METHOD__);
788
+		$startTime = microtime(true);
791 789
 		$requestStatus = $request->execute();
792
-		$endTime = microtime( true );
790
+		$endTime = microtime(true);
793 791
 		$this->dataFactory->timing(
794 792
 			'wikibase.quality.constraints.sparql.timing',
795
-			( $endTime - $startTime ) * 1000
793
+			($endTime - $startTime) * 1000
796 794
 		);
797 795
 
798
-		$this->guardAgainstTooManyRequestsError( $request );
796
+		$this->guardAgainstTooManyRequestsError($request);
799 797
 
800
-		$maxAge = $this->getCacheMaxAge( $request->getResponseHeaders() );
801
-		if ( $maxAge ) {
802
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.cached' );
798
+		$maxAge = $this->getCacheMaxAge($request->getResponseHeaders());
799
+		if ($maxAge) {
800
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.cached');
803 801
 		}
804 802
 
805
-		if ( $requestStatus->isOK() ) {
803
+		if ($requestStatus->isOK()) {
806 804
 			$json = $request->getContent();
807
-			$jsonStatus = FormatJson::parse( $json, FormatJson::FORCE_ASSOC );
808
-			if ( $jsonStatus->isOK() ) {
805
+			$jsonStatus = FormatJson::parse($json, FormatJson::FORCE_ASSOC);
806
+			if ($jsonStatus->isOK()) {
809 807
 				return new CachedQueryResults(
810 808
 					$jsonStatus->getValue(),
811 809
 					Metadata::ofCachingMetadata(
812 810
 						$maxAge ?
813
-							CachingMetadata::ofMaximumAgeInSeconds( $maxAge ) :
814
-							CachingMetadata::fresh()
811
+							CachingMetadata::ofMaximumAgeInSeconds($maxAge) : CachingMetadata::fresh()
815 812
 					)
816 813
 				);
817 814
 			} else {
@@ -828,9 +825,9 @@  discard block
 block discarded – undo
828 825
 			// fall through to general error handling
829 826
 		}
830 827
 
831
-		$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.error' );
828
+		$this->dataFactory->increment('wikibase.quality.constraints.sparql.error');
832 829
 
833
-		if ( $this->isTimeout( $request->getContent() ) ) {
830
+		if ($this->isTimeout($request->getContent())) {
834 831
 			$this->dataFactory->increment(
835 832
 				'wikibase.quality.constraints.sparql.error.timeout'
836 833
 			);
@@ -845,29 +842,29 @@  discard block
 block discarded – undo
845 842
 	 * @param MWHttpRequest $request
846 843
 	 * @throws TooManySparqlRequestsException
847 844
 	 */
848
-	private function guardAgainstTooManyRequestsError( MWHttpRequest $request ): void {
849
-		if ( $request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS ) {
845
+	private function guardAgainstTooManyRequestsError(MWHttpRequest $request): void {
846
+		if ($request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS) {
850 847
 			return;
851 848
 		}
852 849
 
853 850
 		$fallbackBlockDuration = $this->sparqlThrottlingFallbackDuration;
854 851
 
855
-		if ( $fallbackBlockDuration < 0 ) {
856
-			throw new InvalidArgumentException( 'Fallback duration must be positive int but is: ' .
857
-				$fallbackBlockDuration );
852
+		if ($fallbackBlockDuration < 0) {
853
+			throw new InvalidArgumentException('Fallback duration must be positive int but is: '.
854
+				$fallbackBlockDuration);
858 855
 		}
859 856
 
860
-		$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.throttling' );
861
-		$throttlingUntil = $this->getThrottling( $request );
862
-		if ( !( $throttlingUntil instanceof ConvertibleTimestamp ) ) {
863
-			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid( $request );
857
+		$this->dataFactory->increment('wikibase.quality.constraints.sparql.throttling');
858
+		$throttlingUntil = $this->getThrottling($request);
859
+		if (!($throttlingUntil instanceof ConvertibleTimestamp)) {
860
+			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid($request);
864 861
 			$this->throttlingLock->lock(
865 862
 				self::EXPIRY_LOCK_ID,
866
-				$this->getTimestampInFuture( new DateInterval( 'PT' . $fallbackBlockDuration . 'S' ) )
863
+				$this->getTimestampInFuture(new DateInterval('PT'.$fallbackBlockDuration.'S'))
867 864
 			);
868 865
 		} else {
869
-			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent( $throttlingUntil, $request );
870
-			$this->throttlingLock->lock( self::EXPIRY_LOCK_ID, $throttlingUntil );
866
+			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent($throttlingUntil, $request);
867
+			$this->throttlingLock->lock(self::EXPIRY_LOCK_ID, $throttlingUntil);
871 868
 		}
872 869
 		throw new TooManySparqlRequestsException();
873 870
 	}
Please login to merge, or discard this patch.