Completed
Push — master ( ab49f8...a25822 )
by
unknown
01:56
created
src/ServiceWiring.php 1 patch
Spacing   +122 added lines, -122 removed lines patch added patch discarded remove patch
@@ -28,46 +28,46 @@  discard block
 block discarded – undo
28 28
 use WikibaseQuality\ConstraintReport\ConstraintCheck\Result\CheckResultSerializer;
29 29
 
30 30
 return [
31
-	ConstraintsServices::EXPIRY_LOCK => function ( MediaWikiServices $services ) {
32
-		return new ExpiryLock( ObjectCache::getInstance( CACHE_ANYTHING ) );
31
+	ConstraintsServices::EXPIRY_LOCK => function(MediaWikiServices $services) {
32
+		return new ExpiryLock(ObjectCache::getInstance(CACHE_ANYTHING));
33 33
 	},
34 34
 
35
-	ConstraintsServices::LOGGING_HELPER => function ( MediaWikiServices $services ) {
35
+	ConstraintsServices::LOGGING_HELPER => function(MediaWikiServices $services) {
36 36
 		return new LoggingHelper(
37 37
 			$services->getStatsdDataFactory(),
38
-			LoggerFactory::getInstance( 'WikibaseQualityConstraints' ),
38
+			LoggerFactory::getInstance('WikibaseQualityConstraints'),
39 39
 			$services->getMainConfig()
40 40
 		);
41 41
 	},
42 42
 
43
-	ConstraintsServices::CONSTRAINT_STORE => function ( MediaWikiServices $services ) {
43
+	ConstraintsServices::CONSTRAINT_STORE => function(MediaWikiServices $services) {
44 44
 		$wbRepo = WikibaseRepo::getDefaultInstance();
45
-		$sourceDefinitions = WikibaseRepo::getEntitySourceDefinitions( $services );
46
-		$propertySource = $sourceDefinitions->getSourceForEntityType( Property::ENTITY_TYPE );
45
+		$sourceDefinitions = WikibaseRepo::getEntitySourceDefinitions($services);
46
+		$propertySource = $sourceDefinitions->getSourceForEntityType(Property::ENTITY_TYPE);
47 47
 		$dbName = $propertySource->getDatabaseName();
48 48
 
49
-		if ( $propertySource->getSourceName() !== $wbRepo->getLocalEntitySource()->getSourceName() ) {
50
-			throw new \RuntimeException( 'Can\'t get a ConstraintStore for a non local entity source.' );
49
+		if ($propertySource->getSourceName() !== $wbRepo->getLocalEntitySource()->getSourceName()) {
50
+			throw new \RuntimeException('Can\'t get a ConstraintStore for a non local entity source.');
51 51
 		}
52 52
 
53 53
 		return new ConstraintRepositoryStore(
54
-			$services->getDBLoadBalancerFactory()->getMainLB( $dbName ),
54
+			$services->getDBLoadBalancerFactory()->getMainLB($dbName),
55 55
 			$dbName
56 56
 		);
57 57
 	},
58 58
 
59
-	ConstraintsServices::CONSTRAINT_LOOKUP => function ( MediaWikiServices $services ) {
60
-		$sourceDefinitions = WikibaseRepo::getEntitySourceDefinitions( $services );
61
-		$propertySource = $sourceDefinitions->getSourceForEntityType( Property::ENTITY_TYPE );
59
+	ConstraintsServices::CONSTRAINT_LOOKUP => function(MediaWikiServices $services) {
60
+		$sourceDefinitions = WikibaseRepo::getEntitySourceDefinitions($services);
61
+		$propertySource = $sourceDefinitions->getSourceForEntityType(Property::ENTITY_TYPE);
62 62
 		$dbName = $propertySource->getDatabaseName();
63 63
 		$rawLookup = new ConstraintRepositoryLookup(
64
-			$services->getDBLoadBalancerFactory()->getMainLB( $dbName ),
64
+			$services->getDBLoadBalancerFactory()->getMainLB($dbName),
65 65
 			$dbName
66 66
 		);
67
-		return new CachingConstraintLookup( $rawLookup );
67
+		return new CachingConstraintLookup($rawLookup);
68 68
 	},
69 69
 
70
-	ConstraintsServices::CHECK_RESULT_SERIALIZER => function ( MediaWikiServices $services ) {
70
+	ConstraintsServices::CHECK_RESULT_SERIALIZER => function(MediaWikiServices $services) {
71 71
 		return new CheckResultSerializer(
72 72
 			new ConstraintSerializer(
73 73
 				false // constraint parameters are not exposed
@@ -78,10 +78,10 @@  discard block
 block discarded – undo
78 78
 		);
79 79
 	},
80 80
 
81
-	ConstraintsServices::CHECK_RESULT_DESERIALIZER => function ( MediaWikiServices $services ) {
81
+	ConstraintsServices::CHECK_RESULT_DESERIALIZER => function(MediaWikiServices $services) {
82 82
 		// TODO in the future, get DataValueFactory from $services?
83 83
 		$repo = WikibaseRepo::getDefaultInstance();
84
-		$entityIdParser = WikibaseRepo::getEntityIdParser( $services );
84
+		$entityIdParser = WikibaseRepo::getEntityIdParser($services);
85 85
 		$dataValueFactory = $repo->getDataValueFactory();
86 86
 
87 87
 		return new CheckResultDeserializer(
@@ -95,14 +95,14 @@  discard block
 block discarded – undo
95 95
 		);
96 96
 	},
97 97
 
98
-	ConstraintsServices::VIOLATION_MESSAGE_SERIALIZER => function ( MediaWikiServices $services ) {
98
+	ConstraintsServices::VIOLATION_MESSAGE_SERIALIZER => function(MediaWikiServices $services) {
99 99
 		return new ViolationMessageSerializer();
100 100
 	},
101 101
 
102
-	ConstraintsServices::VIOLATION_MESSAGE_DESERIALIZER => function ( MediaWikiServices $services ) {
102
+	ConstraintsServices::VIOLATION_MESSAGE_DESERIALIZER => function(MediaWikiServices $services) {
103 103
 		// TODO in the future, get DataValueFactory from $services?
104 104
 		$repo = WikibaseRepo::getDefaultInstance();
105
-		$entityIdParser = WikibaseRepo::getEntityIdParser( $services );
105
+		$entityIdParser = WikibaseRepo::getEntityIdParser($services);
106 106
 		$dataValueFactory = $repo->getDataValueFactory();
107 107
 
108 108
 		return new ViolationMessageDeserializer(
@@ -111,24 +111,24 @@  discard block
 block discarded – undo
111 111
 		);
112 112
 	},
113 113
 
114
-	ConstraintsServices::CONSTRAINT_PARAMETER_PARSER => function ( MediaWikiServices $services ) {
114
+	ConstraintsServices::CONSTRAINT_PARAMETER_PARSER => function(MediaWikiServices $services) {
115 115
 		// TODO in the future, get DeserializerFactory from $services?
116 116
 		$repo = WikibaseRepo::getDefaultInstance();
117 117
 		$deserializerFactory = $repo->getBaseDataModelDeserializerFactory();
118
-		$entitySourceDefinitions = WikibaseRepo::getEntitySourceDefinitions( $services );
118
+		$entitySourceDefinitions = WikibaseRepo::getEntitySourceDefinitions($services);
119 119
 
120 120
 		return new ConstraintParameterParser(
121 121
 			$services->getMainConfig(),
122 122
 			$deserializerFactory,
123
-			$entitySourceDefinitions->getSourceForEntityType( 'item' )->getConceptBaseUri()
123
+			$entitySourceDefinitions->getSourceForEntityType('item')->getConceptBaseUri()
124 124
 		);
125 125
 	},
126 126
 
127
-	ConstraintsServices::CONNECTION_CHECKER_HELPER => function ( MediaWikiServices $services ) {
127
+	ConstraintsServices::CONNECTION_CHECKER_HELPER => function(MediaWikiServices $services) {
128 128
 		return new ConnectionCheckerHelper();
129 129
 	},
130 130
 
131
-	ConstraintsServices::RANGE_CHECKER_HELPER => function ( MediaWikiServices $services ) {
131
+	ConstraintsServices::RANGE_CHECKER_HELPER => function(MediaWikiServices $services) {
132 132
 		// TODO in the future, get UnitConverter from $services?
133 133
 		$repo = WikibaseRepo::getDefaultInstance();
134 134
 		$unitConverter = $repo->getUnitConverter();
@@ -139,16 +139,16 @@  discard block
 block discarded – undo
139 139
 		);
140 140
 	},
141 141
 
142
-	ConstraintsServices::SPARQL_HELPER => function ( MediaWikiServices $services ) {
143
-		$endpoint = $services->getMainConfig()->get( 'WBQualityConstraintsSparqlEndpoint' );
144
-		if ( $endpoint === '' ) {
142
+	ConstraintsServices::SPARQL_HELPER => function(MediaWikiServices $services) {
143
+		$endpoint = $services->getMainConfig()->get('WBQualityConstraintsSparqlEndpoint');
144
+		if ($endpoint === '') {
145 145
 			return new DummySparqlHelper();
146 146
 		}
147 147
 
148 148
 		// TODO in the future, get RDFVocabulary and PropertyDataTypeLookup from $services?
149 149
 		$repo = WikibaseRepo::getDefaultInstance();
150 150
 		$rdfVocabulary = $repo->getRdfVocabulary();
151
-		$entityIdParser = WikibaseRepo::getEntityIdParser( $services );
151
+		$entityIdParser = WikibaseRepo::getEntityIdParser($services);
152 152
 		$propertyDataTypeLookup = $repo->getPropertyDataTypeLookup();
153 153
 
154 154
 		return new SparqlHelper(
@@ -157,123 +157,123 @@  discard block
 block discarded – undo
157 157
 			$entityIdParser,
158 158
 			$propertyDataTypeLookup,
159 159
 			$services->getMainWANObjectCache(),
160
-			ConstraintsServices::getViolationMessageSerializer( $services ),
161
-			ConstraintsServices::getViolationMessageDeserializer( $services ),
160
+			ConstraintsServices::getViolationMessageSerializer($services),
161
+			ConstraintsServices::getViolationMessageDeserializer($services),
162 162
 			$services->getStatsdDataFactory(),
163
-			ConstraintsServices::getExpiryLock( $services ),
163
+			ConstraintsServices::getExpiryLock($services),
164 164
 			ConstraintsServices::getLoggingHelper(),
165
-			wfWikiID() . ' WikibaseQualityConstraints ' . Http::userAgent(),
165
+			wfWikiID().' WikibaseQualityConstraints '.Http::userAgent(),
166 166
 			$services->getHttpRequestFactory()
167 167
 		);
168 168
 	},
169 169
 
170
-	ConstraintsServices::TYPE_CHECKER_HELPER => function ( MediaWikiServices $services ) {
170
+	ConstraintsServices::TYPE_CHECKER_HELPER => function(MediaWikiServices $services) {
171 171
 		return new TypeCheckerHelper(
172
-			WikibaseServices::getEntityLookup( $services ),
172
+			WikibaseServices::getEntityLookup($services),
173 173
 			$services->getMainConfig(),
174
-			ConstraintsServices::getSparqlHelper( $services ),
174
+			ConstraintsServices::getSparqlHelper($services),
175 175
 			$services->getStatsdDataFactory()
176 176
 		);
177 177
 	},
178 178
 
179
-	ConstraintsServices::DELEGATING_CONSTRAINT_CHECKER => function ( MediaWikiServices $services ) {
179
+	ConstraintsServices::DELEGATING_CONSTRAINT_CHECKER => function(MediaWikiServices $services) {
180 180
 		// TODO in the future, get StatementGuidParser from $services?
181 181
 		$repo = WikibaseRepo::getDefaultInstance();
182 182
 		$statementGuidParser = $repo->getStatementGuidParser();
183 183
 
184 184
 		$config = $services->getMainConfig();
185 185
 		$checkerMap = [
186
-			$config->get( 'WBQualityConstraintsConflictsWithConstraintId' )
187
-				=> ConstraintCheckerServices::getConflictsWithChecker( $services ),
188
-			$config->get( 'WBQualityConstraintsItemRequiresClaimConstraintId' )
189
-				=> ConstraintCheckerServices::getItemChecker( $services ),
190
-			$config->get( 'WBQualityConstraintsValueRequiresClaimConstraintId' )
191
-				=> ConstraintCheckerServices::getTargetRequiredClaimChecker( $services ),
192
-			$config->get( 'WBQualityConstraintsSymmetricConstraintId' )
193
-				=> ConstraintCheckerServices::getSymmetricChecker( $services ),
194
-			$config->get( 'WBQualityConstraintsInverseConstraintId' )
195
-				=> ConstraintCheckerServices::getInverseChecker( $services ),
196
-			$config->get( 'WBQualityConstraintsUsedAsQualifierConstraintId' )
197
-				=> ConstraintCheckerServices::getQualifierChecker( $services ),
198
-			$config->get( 'WBQualityConstraintsAllowedQualifiersConstraintId' )
199
-				=> ConstraintCheckerServices::getQualifiersChecker( $services ),
200
-			$config->get( 'WBQualityConstraintsMandatoryQualifierConstraintId' )
201
-				=> ConstraintCheckerServices::getMandatoryQualifiersChecker( $services ),
202
-			$config->get( 'WBQualityConstraintsRangeConstraintId' )
203
-				=> ConstraintCheckerServices::getRangeChecker( $services ),
204
-			$config->get( 'WBQualityConstraintsDifferenceWithinRangeConstraintId' )
205
-				=> ConstraintCheckerServices::getDiffWithinRangeChecker( $services ),
206
-			$config->get( 'WBQualityConstraintsTypeConstraintId' )
207
-				=> ConstraintCheckerServices::getTypeChecker( $services ),
208
-			$config->get( 'WBQualityConstraintsValueTypeConstraintId' )
209
-				=> ConstraintCheckerServices::getValueTypeChecker( $services ),
210
-			$config->get( 'WBQualityConstraintsSingleValueConstraintId' )
211
-				=> ConstraintCheckerServices::getSingleValueChecker( $services ),
212
-			$config->get( 'WBQualityConstraintsMultiValueConstraintId' )
213
-				=> ConstraintCheckerServices::getMultiValueChecker( $services ),
214
-			$config->get( 'WBQualityConstraintsDistinctValuesConstraintId' )
215
-				=> ConstraintCheckerServices::getUniqueValueChecker( $services ),
216
-			$config->get( 'WBQualityConstraintsFormatConstraintId' )
217
-				=> ConstraintCheckerServices::getFormatChecker( $services ),
218
-			$config->get( 'WBQualityConstraintsCommonsLinkConstraintId' )
219
-				=> ConstraintCheckerServices::getCommonsLinkChecker( $services ),
220
-			$config->get( 'WBQualityConstraintsOneOfConstraintId' )
221
-				=> ConstraintCheckerServices::getOneOfChecker( $services ),
222
-			$config->get( 'WBQualityConstraintsUsedForValuesOnlyConstraintId' )
223
-				=> ConstraintCheckerServices::getValueOnlyChecker( $services ),
224
-			$config->get( 'WBQualityConstraintsUsedAsReferenceConstraintId' )
225
-				=> ConstraintCheckerServices::getReferenceChecker( $services ),
226
-			$config->get( 'WBQualityConstraintsNoBoundsConstraintId' )
227
-				=> ConstraintCheckerServices::getNoBoundsChecker( $services ),
228
-			$config->get( 'WBQualityConstraintsAllowedUnitsConstraintId' )
229
-				=> ConstraintCheckerServices::getAllowedUnitsChecker( $services ),
230
-			$config->get( 'WBQualityConstraintsSingleBestValueConstraintId' )
231
-				=> ConstraintCheckerServices::getSingleBestValueChecker( $services ),
232
-			$config->get( 'WBQualityConstraintsAllowedEntityTypesConstraintId' )
233
-				=> ConstraintCheckerServices::getEntityTypeChecker( $services ),
234
-			$config->get( 'WBQualityConstraintsNoneOfConstraintId' )
235
-				=> ConstraintCheckerServices::getNoneOfChecker( $services ),
236
-			$config->get( 'WBQualityConstraintsIntegerConstraintId' )
237
-				=> ConstraintCheckerServices::getIntegerChecker( $services ),
238
-			$config->get( 'WBQualityConstraintsCitationNeededConstraintId' )
239
-				=> ConstraintCheckerServices::getCitationNeededChecker( $services ),
240
-			$config->get( 'WBQualityConstraintsPropertyScopeConstraintId' )
241
-				=> ConstraintCheckerServices::getPropertyScopeChecker( $services ),
242
-			$config->get( 'WBQualityConstraintsContemporaryConstraintId' )
243
-				=> ConstraintCheckerServices::getContemporaryChecker( $services ),
186
+			$config->get('WBQualityConstraintsConflictsWithConstraintId')
187
+				=> ConstraintCheckerServices::getConflictsWithChecker($services),
188
+			$config->get('WBQualityConstraintsItemRequiresClaimConstraintId')
189
+				=> ConstraintCheckerServices::getItemChecker($services),
190
+			$config->get('WBQualityConstraintsValueRequiresClaimConstraintId')
191
+				=> ConstraintCheckerServices::getTargetRequiredClaimChecker($services),
192
+			$config->get('WBQualityConstraintsSymmetricConstraintId')
193
+				=> ConstraintCheckerServices::getSymmetricChecker($services),
194
+			$config->get('WBQualityConstraintsInverseConstraintId')
195
+				=> ConstraintCheckerServices::getInverseChecker($services),
196
+			$config->get('WBQualityConstraintsUsedAsQualifierConstraintId')
197
+				=> ConstraintCheckerServices::getQualifierChecker($services),
198
+			$config->get('WBQualityConstraintsAllowedQualifiersConstraintId')
199
+				=> ConstraintCheckerServices::getQualifiersChecker($services),
200
+			$config->get('WBQualityConstraintsMandatoryQualifierConstraintId')
201
+				=> ConstraintCheckerServices::getMandatoryQualifiersChecker($services),
202
+			$config->get('WBQualityConstraintsRangeConstraintId')
203
+				=> ConstraintCheckerServices::getRangeChecker($services),
204
+			$config->get('WBQualityConstraintsDifferenceWithinRangeConstraintId')
205
+				=> ConstraintCheckerServices::getDiffWithinRangeChecker($services),
206
+			$config->get('WBQualityConstraintsTypeConstraintId')
207
+				=> ConstraintCheckerServices::getTypeChecker($services),
208
+			$config->get('WBQualityConstraintsValueTypeConstraintId')
209
+				=> ConstraintCheckerServices::getValueTypeChecker($services),
210
+			$config->get('WBQualityConstraintsSingleValueConstraintId')
211
+				=> ConstraintCheckerServices::getSingleValueChecker($services),
212
+			$config->get('WBQualityConstraintsMultiValueConstraintId')
213
+				=> ConstraintCheckerServices::getMultiValueChecker($services),
214
+			$config->get('WBQualityConstraintsDistinctValuesConstraintId')
215
+				=> ConstraintCheckerServices::getUniqueValueChecker($services),
216
+			$config->get('WBQualityConstraintsFormatConstraintId')
217
+				=> ConstraintCheckerServices::getFormatChecker($services),
218
+			$config->get('WBQualityConstraintsCommonsLinkConstraintId')
219
+				=> ConstraintCheckerServices::getCommonsLinkChecker($services),
220
+			$config->get('WBQualityConstraintsOneOfConstraintId')
221
+				=> ConstraintCheckerServices::getOneOfChecker($services),
222
+			$config->get('WBQualityConstraintsUsedForValuesOnlyConstraintId')
223
+				=> ConstraintCheckerServices::getValueOnlyChecker($services),
224
+			$config->get('WBQualityConstraintsUsedAsReferenceConstraintId')
225
+				=> ConstraintCheckerServices::getReferenceChecker($services),
226
+			$config->get('WBQualityConstraintsNoBoundsConstraintId')
227
+				=> ConstraintCheckerServices::getNoBoundsChecker($services),
228
+			$config->get('WBQualityConstraintsAllowedUnitsConstraintId')
229
+				=> ConstraintCheckerServices::getAllowedUnitsChecker($services),
230
+			$config->get('WBQualityConstraintsSingleBestValueConstraintId')
231
+				=> ConstraintCheckerServices::getSingleBestValueChecker($services),
232
+			$config->get('WBQualityConstraintsAllowedEntityTypesConstraintId')
233
+				=> ConstraintCheckerServices::getEntityTypeChecker($services),
234
+			$config->get('WBQualityConstraintsNoneOfConstraintId')
235
+				=> ConstraintCheckerServices::getNoneOfChecker($services),
236
+			$config->get('WBQualityConstraintsIntegerConstraintId')
237
+				=> ConstraintCheckerServices::getIntegerChecker($services),
238
+			$config->get('WBQualityConstraintsCitationNeededConstraintId')
239
+				=> ConstraintCheckerServices::getCitationNeededChecker($services),
240
+			$config->get('WBQualityConstraintsPropertyScopeConstraintId')
241
+				=> ConstraintCheckerServices::getPropertyScopeChecker($services),
242
+			$config->get('WBQualityConstraintsContemporaryConstraintId')
243
+				=> ConstraintCheckerServices::getContemporaryChecker($services),
244 244
 		];
245 245
 
246 246
 		return new DelegatingConstraintChecker(
247
-			WikibaseServices::getEntityLookup( $services ),
247
+			WikibaseServices::getEntityLookup($services),
248 248
 			$checkerMap,
249
-			ConstraintsServices::getConstraintLookup( $services ),
250
-			ConstraintsServices::getConstraintParameterParser( $services ),
249
+			ConstraintsServices::getConstraintLookup($services),
250
+			ConstraintsServices::getConstraintParameterParser($services),
251 251
 			$statementGuidParser,
252
-			ConstraintsServices::getLoggingHelper( $services ),
253
-			$config->get( 'WBQualityConstraintsCheckQualifiers' ),
254
-			$config->get( 'WBQualityConstraintsCheckReferences' ),
255
-			$config->get( 'WBQualityConstraintsPropertiesWithViolatingQualifiers' )
252
+			ConstraintsServices::getLoggingHelper($services),
253
+			$config->get('WBQualityConstraintsCheckQualifiers'),
254
+			$config->get('WBQualityConstraintsCheckReferences'),
255
+			$config->get('WBQualityConstraintsPropertiesWithViolatingQualifiers')
256 256
 		);
257 257
 	},
258 258
 
259
-	ConstraintsServices::RESULTS_SOURCE => function ( MediaWikiServices $services ) {
259
+	ConstraintsServices::RESULTS_SOURCE => function(MediaWikiServices $services) {
260 260
 		$config = $services->getMainConfig();
261 261
 		$resultsSource = new CheckingResultsSource(
262
-			ConstraintsServices::getDelegatingConstraintChecker( $services )
262
+			ConstraintsServices::getDelegatingConstraintChecker($services)
263 263
 		);
264 264
 
265 265
 		$cacheCheckConstraintsResults = false;
266 266
 
267
-		if ( $config->get( 'WBQualityConstraintsCacheCheckConstraintsResults' ) ) {
267
+		if ($config->get('WBQualityConstraintsCacheCheckConstraintsResults')) {
268 268
 			$cacheCheckConstraintsResults = true;
269 269
 			// check that we can use getLocalRepoWikiPageMetaDataAccessor()
270 270
 			// TODO we should always be able to cache constraint check results (T244726)
271 271
 			$repo = WikibaseRepo::getDefaultInstance();
272
-			$entitySources = WikibaseRepo::getEntitySourceDefinitions( $services )->getSources();
273
-			foreach ( $entitySources as $entitySource ) {
274
-				if ( $entitySource->getSourceName() !== $repo->getLocalEntitySource()->getSourceName() ) {
275
-					LoggerFactory::getInstance( 'WikibaseQualityConstraints' )->warning(
276
-						'Cannot cache constraint check results for non-local source: ' .
272
+			$entitySources = WikibaseRepo::getEntitySourceDefinitions($services)->getSources();
273
+			foreach ($entitySources as $entitySource) {
274
+				if ($entitySource->getSourceName() !== $repo->getLocalEntitySource()->getSourceName()) {
275
+					LoggerFactory::getInstance('WikibaseQualityConstraints')->warning(
276
+						'Cannot cache constraint check results for non-local source: '.
277 277
 						$entitySource->getSourceName()
278 278
 					);
279 279
 					$cacheCheckConstraintsResults = false;
@@ -282,29 +282,29 @@  discard block
 block discarded – undo
282 282
 			}
283 283
 		}
284 284
 
285
-		if ( $cacheCheckConstraintsResults ) {
285
+		if ($cacheCheckConstraintsResults) {
286 286
 			$possiblyStaleConstraintTypes = [
287
-				$config->get( 'WBQualityConstraintsCommonsLinkConstraintId' ),
288
-				$config->get( 'WBQualityConstraintsTypeConstraintId' ),
289
-				$config->get( 'WBQualityConstraintsValueTypeConstraintId' ),
290
-				$config->get( 'WBQualityConstraintsDistinctValuesConstraintId' ),
287
+				$config->get('WBQualityConstraintsCommonsLinkConstraintId'),
288
+				$config->get('WBQualityConstraintsTypeConstraintId'),
289
+				$config->get('WBQualityConstraintsValueTypeConstraintId'),
290
+				$config->get('WBQualityConstraintsDistinctValuesConstraintId'),
291 291
 			];
292 292
 			// TODO in the future, get WikiPageEntityMetaDataAccessor from $services?
293 293
 			$repo = WikibaseRepo::getDefaultInstance();
294
-			$entityIdParser = WikibaseRepo::getEntityIdParser( $services );
294
+			$entityIdParser = WikibaseRepo::getEntityIdParser($services);
295 295
 			$wikiPageEntityMetaDataAccessor = $repo->getLocalRepoWikiPageMetaDataAccessor();
296 296
 
297 297
 			$resultsSource = new CachingResultsSource(
298 298
 				$resultsSource,
299 299
 				ResultsCache::getDefaultInstance(),
300
-				ConstraintsServices::getCheckResultSerializer( $services ),
301
-				ConstraintsServices::getCheckResultDeserializer( $services ),
300
+				ConstraintsServices::getCheckResultSerializer($services),
301
+				ConstraintsServices::getCheckResultDeserializer($services),
302 302
 				$wikiPageEntityMetaDataAccessor,
303 303
 				$entityIdParser,
304
-				$config->get( 'WBQualityConstraintsCacheCheckConstraintsTTLSeconds' ),
304
+				$config->get('WBQualityConstraintsCacheCheckConstraintsTTLSeconds'),
305 305
 				$possiblyStaleConstraintTypes,
306
-				$config->get( 'WBQualityConstraintsCacheCheckConstraintsMaximumRevisionIds' ),
307
-				ConstraintsServices::getLoggingHelper( $services )
306
+				$config->get('WBQualityConstraintsCacheCheckConstraintsMaximumRevisionIds'),
307
+				ConstraintsServices::getLoggingHelper($services)
308 308
 			);
309 309
 		}
310 310
 
Please login to merge, or discard this patch.
src/ConstraintCheck/Helper/SparqlHelper.php 1 patch
Spacing   +174 added lines, -177 removed lines patch added patch discarded remove patch
@@ -199,73 +199,73 @@  discard block
 block discarded – undo
199 199
 		$this->defaultUserAgent = $defaultUserAgent;
200 200
 		$this->requestFactory = $requestFactory;
201 201
 		$this->entityPrefixes = [];
202
-		foreach ( $rdfVocabulary->entityNamespaceNames as $namespaceName ) {
203
-			$this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI( $namespaceName );
202
+		foreach ($rdfVocabulary->entityNamespaceNames as $namespaceName) {
203
+			$this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI($namespaceName);
204 204
 		}
205 205
 
206
-		$this->endpoint = $config->get( 'WBQualityConstraintsSparqlEndpoint' );
207
-		$this->maxQueryTimeMillis = $config->get( 'WBQualityConstraintsSparqlMaxMillis' );
208
-		$this->instanceOfId = $config->get( 'WBQualityConstraintsInstanceOfId' );
209
-		$this->subclassOfId = $config->get( 'WBQualityConstraintsSubclassOfId' );
210
-		$this->cacheMapSize = $config->get( 'WBQualityConstraintsFormatCacheMapSize' );
206
+		$this->endpoint = $config->get('WBQualityConstraintsSparqlEndpoint');
207
+		$this->maxQueryTimeMillis = $config->get('WBQualityConstraintsSparqlMaxMillis');
208
+		$this->instanceOfId = $config->get('WBQualityConstraintsInstanceOfId');
209
+		$this->subclassOfId = $config->get('WBQualityConstraintsSubclassOfId');
210
+		$this->cacheMapSize = $config->get('WBQualityConstraintsFormatCacheMapSize');
211 211
 		$this->timeoutExceptionClasses = $config->get(
212 212
 			'WBQualityConstraintsSparqlTimeoutExceptionClasses'
213 213
 		);
214 214
 		$this->sparqlHasWikibaseSupport = $config->get(
215 215
 			'WBQualityConstraintsSparqlHasWikibaseSupport'
216 216
 		);
217
-		$this->sparqlThrottlingFallbackDuration = (int)$config->get(
217
+		$this->sparqlThrottlingFallbackDuration = (int) $config->get(
218 218
 			'WBQualityConstraintsSparqlThrottlingFallbackDuration'
219 219
 		);
220 220
 
221
-		$this->prefixes = $this->getQueryPrefixes( $rdfVocabulary );
221
+		$this->prefixes = $this->getQueryPrefixes($rdfVocabulary);
222 222
 	}
223 223
 
224
-	private function getQueryPrefixes( RdfVocabulary $rdfVocabulary ) {
224
+	private function getQueryPrefixes(RdfVocabulary $rdfVocabulary) {
225 225
 		// TODO: it would probably be smarter that RdfVocubulary exposed these prefixes somehow
226 226
 		$prefixes = '';
227
-		foreach ( $rdfVocabulary->entityNamespaceNames as $sourceName => $namespaceName ) {
227
+		foreach ($rdfVocabulary->entityNamespaceNames as $sourceName => $namespaceName) {
228 228
 			$prefixes .= <<<END
229
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
229
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
230 230
 END;
231 231
 		}
232 232
 		$prefixes .= <<<END
233
-PREFIX wds: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_STATEMENT )}>
234
-PREFIX wdv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_VALUE )}>\n
233
+PREFIX wds: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_STATEMENT)}>
234
+PREFIX wdv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_VALUE)}>\n
235 235
 END;
236 236
 
237
-		foreach ( $rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces ) {
237
+		foreach ($rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces) {
238 238
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_DIRECT_CLAIM];
239 239
 			$prefixes .= <<<END
240
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
240
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
241 241
 END;
242 242
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM];
243 243
 			$prefixes .= <<<END
244
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
244
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
245 245
 END;
246 246
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM_STATEMENT];
247 247
 			$prefixes .= <<<END
248
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
248
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
249 249
 END;
250 250
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER];
251 251
 			$prefixes .= <<<END
252
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
252
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
253 253
 END;
254 254
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER_VALUE];
255 255
 			$prefixes .= <<<END
256
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
256
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
257 257
 END;
258 258
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE];
259 259
 			$prefixes .= <<<END
260
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
260
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
261 261
 END;
262 262
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE_VALUE];
263 263
 			$prefixes .= <<<END
264
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
264
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
265 265
 END;
266 266
 		}
267 267
 		$prefixes .= <<<END
268
-PREFIX wikibase: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_ONTOLOGY )}>\n
268
+PREFIX wikibase: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_ONTOLOGY)}>\n
269 269
 END;
270 270
 		return $prefixes;
271 271
 	}
@@ -277,21 +277,20 @@  discard block
 block discarded – undo
277 277
 	 * @return CachedBool
278 278
 	 * @throws SparqlHelperException if the query times out or some other error occurs
279 279
 	 */
280
-	public function hasType( $id, array $classes ) {
280
+	public function hasType($id, array $classes) {
281 281
 		// TODO hint:gearing is a workaround for T168973 and can hopefully be removed eventually
282 282
 		$gearingHint = $this->sparqlHasWikibaseSupport ?
283
-			' hint:Prior hint:gearing "forward".' :
284
-			'';
283
+			' hint:Prior hint:gearing "forward".' : '';
285 284
 
286 285
 		$metadatas = [];
287 286
 
288
-		foreach ( array_chunk( $classes, 20 ) as $classesChunk ) {
289
-			$classesValues = implode( ' ', array_map(
290
-				function ( $class ) {
291
-					return 'wd:' . $class;
287
+		foreach (array_chunk($classes, 20) as $classesChunk) {
288
+			$classesValues = implode(' ', array_map(
289
+				function($class) {
290
+					return 'wd:'.$class;
292 291
 				},
293 292
 				$classesChunk
294
-			) );
293
+			));
295 294
 
296 295
 			$query = <<<EOF
297 296
 ASK {
@@ -301,19 +300,19 @@  discard block
 block discarded – undo
301 300
 }
302 301
 EOF;
303 302
 
304
-			$result = $this->runQuery( $query );
303
+			$result = $this->runQuery($query);
305 304
 			$metadatas[] = $result->getMetadata();
306
-			if ( $result->getArray()['boolean'] ) {
305
+			if ($result->getArray()['boolean']) {
307 306
 				return new CachedBool(
308 307
 					true,
309
-					Metadata::merge( $metadatas )
308
+					Metadata::merge($metadatas)
310 309
 				);
311 310
 			}
312 311
 		}
313 312
 
314 313
 		return new CachedBool(
315 314
 			false,
316
-			Metadata::merge( $metadatas )
315
+			Metadata::merge($metadatas)
317 316
 		);
318 317
 	}
319 318
 
@@ -329,10 +328,10 @@  discard block
 block discarded – undo
329 328
 		$ignoreDeprecatedStatements
330 329
 	) {
331 330
 		$pid = $statement->getPropertyId()->serialize();
332
-		$guid = str_replace( '$', '-', $statement->getGuid() );
331
+		$guid = str_replace('$', '-', $statement->getGuid());
333 332
 
334 333
 		$deprecatedFilter = '';
335
-		if ( $ignoreDeprecatedStatements ) {
334
+		if ($ignoreDeprecatedStatements) {
336 335
 			$deprecatedFilter = 'MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. }';
337 336
 		}
338 337
 
@@ -351,9 +350,9 @@  discard block
 block discarded – undo
351 350
 LIMIT 10
352 351
 EOF;
353 352
 
354
-		$result = $this->runQuery( $query );
353
+		$result = $this->runQuery($query);
355 354
 
356
-		return $this->getOtherEntities( $result );
355
+		return $this->getOtherEntities($result);
357 356
 	}
358 357
 
359 358
 	/**
@@ -378,16 +377,15 @@  discard block
 block discarded – undo
378 377
 		$dataType = $this->propertyDataTypeLookup->getDataTypeIdForProperty(
379 378
 			$snak->getPropertyId()
380 379
 		);
381
-		list( $value, $isFullValue ) = $this->getRdfLiteral( $dataType, $dataValue );
382
-		if ( $isFullValue ) {
380
+		list($value, $isFullValue) = $this->getRdfLiteral($dataType, $dataValue);
381
+		if ($isFullValue) {
383 382
 			$prefix .= 'v';
384 383
 		}
385 384
 		$path = $type === Context::TYPE_QUALIFIER ?
386
-			"$prefix:$pid" :
387
-			"prov:wasDerivedFrom/$prefix:$pid";
385
+			"$prefix:$pid" : "prov:wasDerivedFrom/$prefix:$pid";
388 386
 
389 387
 		$deprecatedFilter = '';
390
-		if ( $ignoreDeprecatedStatements ) {
388
+		if ($ignoreDeprecatedStatements) {
391 389
 			$deprecatedFilter = <<< EOF
392 390
   MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. }
393 391
 EOF;
@@ -407,9 +405,9 @@  discard block
 block discarded – undo
407 405
 LIMIT 10
408 406
 EOF;
409 407
 
410
-		$result = $this->runQuery( $query );
408
+		$result = $this->runQuery($query);
411 409
 
412
-		return $this->getOtherEntities( $result );
410
+		return $this->getOtherEntities($result);
413 411
 	}
414 412
 
415 413
 	/**
@@ -419,8 +417,8 @@  discard block
 block discarded – undo
419 417
 	 *
420 418
 	 * @return string
421 419
 	 */
422
-	private function stringLiteral( $text ) {
423
-		return '"' . strtr( $text, [ '"' => '\\"', '\\' => '\\\\' ] ) . '"';
420
+	private function stringLiteral($text) {
421
+		return '"'.strtr($text, ['"' => '\\"', '\\' => '\\\\']).'"';
424 422
 	}
425 423
 
426 424
 	/**
@@ -430,18 +428,18 @@  discard block
 block discarded – undo
430 428
 	 *
431 429
 	 * @return CachedEntityIds
432 430
 	 */
433
-	private function getOtherEntities( CachedQueryResults $results ) {
434
-		return new CachedEntityIds( array_map(
435
-			function ( $resultBindings ) {
431
+	private function getOtherEntities(CachedQueryResults $results) {
432
+		return new CachedEntityIds(array_map(
433
+			function($resultBindings) {
436 434
 				$entityIRI = $resultBindings['otherEntity']['value'];
437
-				foreach ( $this->entityPrefixes as $entityPrefix ) {
438
-					$entityPrefixLength = strlen( $entityPrefix );
439
-					if ( substr( $entityIRI, 0, $entityPrefixLength ) === $entityPrefix ) {
435
+				foreach ($this->entityPrefixes as $entityPrefix) {
436
+					$entityPrefixLength = strlen($entityPrefix);
437
+					if (substr($entityIRI, 0, $entityPrefixLength) === $entityPrefix) {
440 438
 						try {
441 439
 							return $this->entityIdParser->parse(
442
-								substr( $entityIRI, $entityPrefixLength )
440
+								substr($entityIRI, $entityPrefixLength)
443 441
 							);
444
-						} catch ( EntityIdParsingException $e ) {
442
+						} catch (EntityIdParsingException $e) {
445 443
 							// fall through
446 444
 						}
447 445
 					}
@@ -452,7 +450,7 @@  discard block
 block discarded – undo
452 450
 				return null;
453 451
 			},
454 452
 			$results->getArray()['results']['bindings']
455
-		), $results->getMetadata() );
453
+		), $results->getMetadata());
456 454
 	}
457 455
 
458 456
 	// @codingStandardsIgnoreStart cyclomatic complexity of this function is too high
@@ -465,49 +463,49 @@  discard block
 block discarded – undo
465 463
 	 * @return array the literal or IRI as a string in SPARQL syntax,
466 464
 	 * and a boolean indicating whether it refers to a full value node or not
467 465
 	 */
468
-	private function getRdfLiteral( $dataType, DataValue $dataValue ) {
469
-		switch ( $dataType ) {
466
+	private function getRdfLiteral($dataType, DataValue $dataValue) {
467
+		switch ($dataType) {
470 468
 			case 'string':
471 469
 			case 'external-id':
472
-				return [ $this->stringLiteral( $dataValue->getValue() ), false ];
470
+				return [$this->stringLiteral($dataValue->getValue()), false];
473 471
 			case 'commonsMedia':
474
-				$url = $this->rdfVocabulary->getMediaFileURI( $dataValue->getValue() );
475
-				return [ '<' . $url . '>', false ];
472
+				$url = $this->rdfVocabulary->getMediaFileURI($dataValue->getValue());
473
+				return ['<'.$url.'>', false];
476 474
 			case 'geo-shape':
477
-				$url = $this->rdfVocabulary->getGeoShapeURI( $dataValue->getValue() );
478
-				return [ '<' . $url . '>', false ];
475
+				$url = $this->rdfVocabulary->getGeoShapeURI($dataValue->getValue());
476
+				return ['<'.$url.'>', false];
479 477
 			case 'tabular-data':
480
-				$url = $this->rdfVocabulary->getTabularDataURI( $dataValue->getValue() );
481
-				return [ '<' . $url . '>', false ];
478
+				$url = $this->rdfVocabulary->getTabularDataURI($dataValue->getValue());
479
+				return ['<'.$url.'>', false];
482 480
 			case 'url':
483 481
 				$url = $dataValue->getValue();
484
-				if ( !preg_match( '/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url ) ) {
482
+				if (!preg_match('/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url)) {
485 483
 					// not a valid URL for SPARQL (see SPARQL spec, production 139 IRIREF)
486 484
 					// such an URL should never reach us, so just throw
487
-					throw new InvalidArgumentException( 'invalid URL: ' . $url );
485
+					throw new InvalidArgumentException('invalid URL: '.$url);
488 486
 				}
489
-				return [ '<' . $url . '>', false ];
487
+				return ['<'.$url.'>', false];
490 488
 			case 'wikibase-item':
491 489
 			case 'wikibase-property':
492 490
 				/** @var EntityIdValue $dataValue */
493 491
 				'@phan-var EntityIdValue $dataValue';
494
-				return [ 'wd:' . $dataValue->getEntityId()->getSerialization(), false ];
492
+				return ['wd:'.$dataValue->getEntityId()->getSerialization(), false];
495 493
 			case 'monolingualtext':
496 494
 				/** @var MonolingualTextValue $dataValue */
497 495
 				'@phan-var MonolingualTextValue $dataValue';
498 496
 				$lang = $dataValue->getLanguageCode();
499
-				if ( !preg_match( '/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang ) ) {
497
+				if (!preg_match('/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang)) {
500 498
 					// not a valid language tag for SPARQL (see SPARQL spec, production 145 LANGTAG)
501 499
 					// such a language tag should never reach us, so just throw
502
-					throw new InvalidArgumentException( 'invalid language tag: ' . $lang );
500
+					throw new InvalidArgumentException('invalid language tag: '.$lang);
503 501
 				}
504
-				return [ $this->stringLiteral( $dataValue->getText() ) . '@' . $lang, false ];
502
+				return [$this->stringLiteral($dataValue->getText()).'@'.$lang, false];
505 503
 			case 'globe-coordinate':
506 504
 			case 'quantity':
507 505
 			case 'time':
508
-				return [ 'wdv:' . $dataValue->getHash(), true ];
506
+				return ['wdv:'.$dataValue->getHash(), true];
509 507
 			default:
510
-				throw new InvalidArgumentException( 'unknown data type: ' . $dataType );
508
+				throw new InvalidArgumentException('unknown data type: '.$dataType);
511 509
 		}
512 510
 	}
513 511
 	// @codingStandardsIgnoreEnd
@@ -520,43 +518,43 @@  discard block
 block discarded – undo
520 518
 	 * @throws SparqlHelperException if the query times out or some other error occurs
521 519
 	 * @throws ConstraintParameterException if the $regex is invalid
522 520
 	 */
523
-	public function matchesRegularExpression( $text, $regex ) {
521
+	public function matchesRegularExpression($text, $regex) {
524 522
 		// caching wrapper around matchesRegularExpressionWithSparql
525 523
 
526
-		$textHash = hash( 'sha256', $text );
524
+		$textHash = hash('sha256', $text);
527 525
 		$cacheKey = $this->cache->makeKey(
528 526
 			'WikibaseQualityConstraints', // extension
529 527
 			'regex', // action
530 528
 			'WDQS-Java', // regex flavor
531
-			hash( 'sha256', $regex )
529
+			hash('sha256', $regex)
532 530
 		);
533 531
 
534 532
 		$cacheMapArray = $this->cache->getWithSetCallback(
535 533
 			$cacheKey,
536 534
 			WANObjectCache::TTL_DAY,
537
-			function ( $cacheMapArray ) use ( $text, $regex, $textHash ) {
535
+			function($cacheMapArray) use ($text, $regex, $textHash) {
538 536
 				// Initialize the cache map if not set
539
-				if ( $cacheMapArray === false ) {
537
+				if ($cacheMapArray === false) {
540 538
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.init';
541
-					$this->dataFactory->increment( $key );
539
+					$this->dataFactory->increment($key);
542 540
 					return [];
543 541
 				}
544 542
 
545 543
 				$key = 'wikibase.quality.constraints.regex.cache.refresh';
546
-				$this->dataFactory->increment( $key );
547
-				$cacheMap = MapCacheLRU::newFromArray( $cacheMapArray, $this->cacheMapSize );
548
-				if ( $cacheMap->has( $textHash ) ) {
544
+				$this->dataFactory->increment($key);
545
+				$cacheMap = MapCacheLRU::newFromArray($cacheMapArray, $this->cacheMapSize);
546
+				if ($cacheMap->has($textHash)) {
549 547
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.hit';
550
-					$this->dataFactory->increment( $key );
551
-					$cacheMap->get( $textHash ); // ping cache
548
+					$this->dataFactory->increment($key);
549
+					$cacheMap->get($textHash); // ping cache
552 550
 				} else {
553 551
 					$key = 'wikibase.quality.constraints.regex.cache.refresh.miss';
554
-					$this->dataFactory->increment( $key );
552
+					$this->dataFactory->increment($key);
555 553
 					try {
556
-						$matches = $this->matchesRegularExpressionWithSparql( $text, $regex );
557
-					} catch ( ConstraintParameterException $e ) {
558
-						$matches = $this->serializeConstraintParameterException( $e );
559
-					} catch ( SparqlHelperException $e ) {
554
+						$matches = $this->matchesRegularExpressionWithSparql($text, $regex);
555
+					} catch (ConstraintParameterException $e) {
556
+						$matches = $this->serializeConstraintParameterException($e);
557
+					} catch (SparqlHelperException $e) {
560 558
 						// don’t cache this
561 559
 						return $cacheMap->toArray();
562 560
 					}
@@ -580,42 +578,42 @@  discard block
 block discarded – undo
580 578
 			]
581 579
 		);
582 580
 
583
-		if ( isset( $cacheMapArray[$textHash] ) ) {
581
+		if (isset($cacheMapArray[$textHash])) {
584 582
 			$key = 'wikibase.quality.constraints.regex.cache.hit';
585
-			$this->dataFactory->increment( $key );
583
+			$this->dataFactory->increment($key);
586 584
 			$matches = $cacheMapArray[$textHash];
587
-			if ( is_bool( $matches ) ) {
585
+			if (is_bool($matches)) {
588 586
 				return $matches;
589
-			} elseif ( is_array( $matches ) &&
590
-				$matches['type'] == ConstraintParameterException::class ) {
591
-				throw $this->deserializeConstraintParameterException( $matches );
587
+			} elseif (is_array($matches) &&
588
+				$matches['type'] == ConstraintParameterException::class) {
589
+				throw $this->deserializeConstraintParameterException($matches);
592 590
 			} else {
593 591
 				throw new MWException(
594
-					'Value of unknown type in object cache (' .
595
-					'cache key: ' . $cacheKey . ', ' .
596
-					'cache map key: ' . $textHash . ', ' .
597
-					'value type: ' . gettype( $matches ) . ')'
592
+					'Value of unknown type in object cache ('.
593
+					'cache key: '.$cacheKey.', '.
594
+					'cache map key: '.$textHash.', '.
595
+					'value type: '.gettype($matches).')'
598 596
 				);
599 597
 			}
600 598
 		} else {
601 599
 			$key = 'wikibase.quality.constraints.regex.cache.miss';
602
-			$this->dataFactory->increment( $key );
603
-			return $this->matchesRegularExpressionWithSparql( $text, $regex );
600
+			$this->dataFactory->increment($key);
601
+			return $this->matchesRegularExpressionWithSparql($text, $regex);
604 602
 		}
605 603
 	}
606 604
 
607
-	private function serializeConstraintParameterException( ConstraintParameterException $cpe ) {
605
+	private function serializeConstraintParameterException(ConstraintParameterException $cpe) {
608 606
 		return [
609 607
 			'type' => ConstraintParameterException::class,
610
-			'violationMessage' => $this->violationMessageSerializer->serialize( $cpe->getViolationMessage() ),
608
+			'violationMessage' => $this->violationMessageSerializer->serialize($cpe->getViolationMessage()),
611 609
 		];
612 610
 	}
613 611
 
614
-	private function deserializeConstraintParameterException( array $serialization ) {
612
+	private function deserializeConstraintParameterException(array $serialization) {
615 613
 		$message = $this->violationMessageDeserializer->deserialize(
616 614
 			$serialization['violationMessage']
617 615
 		);
618
-		return new ConstraintParameterException( $message );
616
+		return new ConstraintParameterException($message);
619 617
 	}
620 618
 
621 619
 	/**
@@ -629,25 +627,25 @@  discard block
 block discarded – undo
629 627
 	 * @throws SparqlHelperException if the query times out or some other error occurs
630 628
 	 * @throws ConstraintParameterException if the $regex is invalid
631 629
 	 */
632
-	public function matchesRegularExpressionWithSparql( $text, $regex ) {
633
-		$textStringLiteral = $this->stringLiteral( $text );
634
-		$regexStringLiteral = $this->stringLiteral( '^(?:' . $regex . ')$' );
630
+	public function matchesRegularExpressionWithSparql($text, $regex) {
631
+		$textStringLiteral = $this->stringLiteral($text);
632
+		$regexStringLiteral = $this->stringLiteral('^(?:'.$regex.')$');
635 633
 
636 634
 		$query = <<<EOF
637 635
 SELECT (REGEX($textStringLiteral, $regexStringLiteral) AS ?matches) {}
638 636
 EOF;
639 637
 
640
-		$result = $this->runQuery( $query, false );
638
+		$result = $this->runQuery($query, false);
641 639
 
642 640
 		$vars = $result->getArray()['results']['bindings'][0];
643
-		if ( array_key_exists( 'matches', $vars ) ) {
641
+		if (array_key_exists('matches', $vars)) {
644 642
 			// true or false ⇒ regex okay, text matches or not
645 643
 			return $vars['matches']['value'] === 'true';
646 644
 		} else {
647 645
 			// empty result: regex broken
648 646
 			throw new ConstraintParameterException(
649
-				( new ViolationMessage( 'wbqc-violation-message-parameter-regex' ) )
650
-					->withInlineCode( $regex, Role::CONSTRAINT_PARAMETER_VALUE )
647
+				(new ViolationMessage('wbqc-violation-message-parameter-regex'))
648
+					->withInlineCode($regex, Role::CONSTRAINT_PARAMETER_VALUE)
651 649
 			);
652 650
 		}
653 651
 	}
@@ -659,14 +657,14 @@  discard block
 block discarded – undo
659 657
 	 *
660 658
 	 * @return boolean
661 659
 	 */
662
-	public function isTimeout( $responseContent ) {
663
-		$timeoutRegex = implode( '|', array_map(
664
-			function ( $fqn ) {
665
-				return preg_quote( $fqn, '/' );
660
+	public function isTimeout($responseContent) {
661
+		$timeoutRegex = implode('|', array_map(
662
+			function($fqn) {
663
+				return preg_quote($fqn, '/');
666 664
 			},
667 665
 			$this->timeoutExceptionClasses
668
-		) );
669
-		return (bool)preg_match( '/' . $timeoutRegex . '/', $responseContent );
666
+		));
667
+		return (bool) preg_match('/'.$timeoutRegex.'/', $responseContent);
670 668
 	}
671 669
 
672 670
 	/**
@@ -678,17 +676,17 @@  discard block
 block discarded – undo
678 676
 	 * @return int|boolean the max-age (in seconds)
679 677
 	 * or a plain boolean if no max-age can be determined
680 678
 	 */
681
-	public function getCacheMaxAge( $responseHeaders ) {
679
+	public function getCacheMaxAge($responseHeaders) {
682 680
 		if (
683
-			array_key_exists( 'x-cache-status', $responseHeaders ) &&
684
-			preg_match( '/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0] )
681
+			array_key_exists('x-cache-status', $responseHeaders) &&
682
+			preg_match('/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0])
685 683
 		) {
686 684
 			$maxage = [];
687 685
 			if (
688
-				array_key_exists( 'cache-control', $responseHeaders ) &&
689
-				preg_match( '/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage )
686
+				array_key_exists('cache-control', $responseHeaders) &&
687
+				preg_match('/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage)
690 688
 			) {
691
-				return intval( $maxage[1] );
689
+				return intval($maxage[1]);
692 690
 			} else {
693 691
 				return true;
694 692
 			}
@@ -709,34 +707,34 @@  discard block
 block discarded – undo
709 707
 	 * or SparlHelper::EMPTY_RETRY_AFTER if there is an empty Retry-After
710 708
 	 * or SparlHelper::INVALID_RETRY_AFTER if there is something wrong with the format
711 709
 	 */
712
-	public function getThrottling( MWHttpRequest $request ) {
713
-		$retryAfterValue = $request->getResponseHeader( 'Retry-After' );
714
-		if ( $retryAfterValue === null ) {
710
+	public function getThrottling(MWHttpRequest $request) {
711
+		$retryAfterValue = $request->getResponseHeader('Retry-After');
712
+		if ($retryAfterValue === null) {
715 713
 			return self::NO_RETRY_AFTER;
716 714
 		}
717 715
 
718
-		$trimmedRetryAfterValue = trim( $retryAfterValue );
719
-		if ( empty( $trimmedRetryAfterValue ) ) {
716
+		$trimmedRetryAfterValue = trim($retryAfterValue);
717
+		if (empty($trimmedRetryAfterValue)) {
720 718
 			return self::EMPTY_RETRY_AFTER;
721 719
 		}
722 720
 
723
-		if ( is_numeric( $trimmedRetryAfterValue ) ) {
724
-			$delaySeconds = (int)$trimmedRetryAfterValue;
725
-			if ( $delaySeconds >= 0 ) {
726
-				return $this->getTimestampInFuture( new DateInterval( 'PT' . $delaySeconds . 'S' ) );
721
+		if (is_numeric($trimmedRetryAfterValue)) {
722
+			$delaySeconds = (int) $trimmedRetryAfterValue;
723
+			if ($delaySeconds >= 0) {
724
+				return $this->getTimestampInFuture(new DateInterval('PT'.$delaySeconds.'S'));
727 725
 			}
728 726
 		} else {
729
-			$return = strtotime( $trimmedRetryAfterValue );
730
-			if ( !empty( $return ) ) {
731
-				return new ConvertibleTimestamp( $return );
727
+			$return = strtotime($trimmedRetryAfterValue);
728
+			if (!empty($return)) {
729
+				return new ConvertibleTimestamp($return);
732 730
 			}
733 731
 		}
734 732
 		return self::INVALID_RETRY_AFTER;
735 733
 	}
736 734
 
737
-	private function getTimestampInFuture( DateInterval $delta ) {
735
+	private function getTimestampInFuture(DateInterval $delta) {
738 736
 		$now = new ConvertibleTimestamp();
739
-		return new ConvertibleTimestamp( $now->timestamp->add( $delta ) );
737
+		return new ConvertibleTimestamp($now->timestamp->add($delta));
740 738
 	}
741 739
 
742 740
 	/**
@@ -750,65 +748,64 @@  discard block
 block discarded – undo
750 748
 	 *
751 749
 	 * @throws SparqlHelperException if the query times out or some other error occurs
752 750
 	 */
753
-	public function runQuery( $query, $needsPrefixes = true ) {
751
+	public function runQuery($query, $needsPrefixes = true) {
754 752
 
755
-		if ( $this->throttlingLock->isLocked( self::EXPIRY_LOCK_ID ) ) {
756
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.throttling' );
753
+		if ($this->throttlingLock->isLocked(self::EXPIRY_LOCK_ID)) {
754
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.throttling');
757 755
 			throw new TooManySparqlRequestsException();
758 756
 		}
759 757
 
760
-		if ( $this->sparqlHasWikibaseSupport ) {
758
+		if ($this->sparqlHasWikibaseSupport) {
761 759
 			$needsPrefixes = false;
762 760
 		}
763 761
 
764
-		if ( $needsPrefixes ) {
765
-			$query = $this->prefixes . $query;
762
+		if ($needsPrefixes) {
763
+			$query = $this->prefixes.$query;
766 764
 		}
767
-		$query = "#wbqc\n" . $query;
765
+		$query = "#wbqc\n".$query;
768 766
 
769
-		$url = $this->endpoint . '?' . http_build_query(
767
+		$url = $this->endpoint.'?'.http_build_query(
770 768
 			[
771 769
 				'query' => $query,
772 770
 				'format' => 'json',
773 771
 				'maxQueryTimeMillis' => $this->maxQueryTimeMillis,
774 772
 			],
775
-			null, ini_get( 'arg_separator.output' ),
773
+			null, ini_get('arg_separator.output'),
776 774
 			// encode spaces with %20, not +
777 775
 			PHP_QUERY_RFC3986
778 776
 		);
779 777
 
780 778
 		$options = [
781 779
 			'method' => 'GET',
782
-			'timeout' => (int)round( ( $this->maxQueryTimeMillis + 1000 ) / 1000 ),
780
+			'timeout' => (int) round(($this->maxQueryTimeMillis + 1000) / 1000),
783 781
 			'connectTimeout' => 'default',
784 782
 			'userAgent' => $this->defaultUserAgent,
785 783
 		];
786
-		$request = $this->requestFactory->create( $url, $options, __METHOD__ );
787
-		$startTime = microtime( true );
784
+		$request = $this->requestFactory->create($url, $options, __METHOD__);
785
+		$startTime = microtime(true);
788 786
 		$requestStatus = $request->execute();
789
-		$endTime = microtime( true );
787
+		$endTime = microtime(true);
790 788
 		$this->dataFactory->timing(
791 789
 			'wikibase.quality.constraints.sparql.timing',
792
-			( $endTime - $startTime ) * 1000
790
+			($endTime - $startTime) * 1000
793 791
 		);
794 792
 
795
-		$this->guardAgainstTooManyRequestsError( $request );
793
+		$this->guardAgainstTooManyRequestsError($request);
796 794
 
797
-		$maxAge = $this->getCacheMaxAge( $request->getResponseHeaders() );
798
-		if ( $maxAge ) {
799
-			$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.cached' );
795
+		$maxAge = $this->getCacheMaxAge($request->getResponseHeaders());
796
+		if ($maxAge) {
797
+			$this->dataFactory->increment('wikibase.quality.constraints.sparql.cached');
800 798
 		}
801 799
 
802
-		if ( $requestStatus->isOK() ) {
800
+		if ($requestStatus->isOK()) {
803 801
 			$json = $request->getContent();
804
-			$jsonStatus = FormatJson::parse( $json, FormatJson::FORCE_ASSOC );
805
-			if ( $jsonStatus->isOK() ) {
802
+			$jsonStatus = FormatJson::parse($json, FormatJson::FORCE_ASSOC);
803
+			if ($jsonStatus->isOK()) {
806 804
 				return new CachedQueryResults(
807 805
 					$jsonStatus->getValue(),
808 806
 					Metadata::ofCachingMetadata(
809 807
 						$maxAge ?
810
-							CachingMetadata::ofMaximumAgeInSeconds( $maxAge ) :
811
-							CachingMetadata::fresh()
808
+							CachingMetadata::ofMaximumAgeInSeconds($maxAge) : CachingMetadata::fresh()
812 809
 					)
813 810
 				);
814 811
 			} else {
@@ -825,9 +822,9 @@  discard block
 block discarded – undo
825 822
 			// fall through to general error handling
826 823
 		}
827 824
 
828
-		$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.error' );
825
+		$this->dataFactory->increment('wikibase.quality.constraints.sparql.error');
829 826
 
830
-		if ( $this->isTimeout( $request->getContent() ) ) {
827
+		if ($this->isTimeout($request->getContent())) {
831 828
 			$this->dataFactory->increment(
832 829
 				'wikibase.quality.constraints.sparql.error.timeout'
833 830
 			);
@@ -842,29 +839,29 @@  discard block
 block discarded – undo
842 839
 	 * @param MWHttpRequest $request
843 840
 	 * @throws TooManySparqlRequestsException
844 841
 	 */
845
-	private function guardAgainstTooManyRequestsError( MWHttpRequest $request ): void {
846
-		if ( $request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS ) {
842
+	private function guardAgainstTooManyRequestsError(MWHttpRequest $request): void {
843
+		if ($request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS) {
847 844
 			return;
848 845
 		}
849 846
 
850 847
 		$fallbackBlockDuration = $this->sparqlThrottlingFallbackDuration;
851 848
 
852
-		if ( $fallbackBlockDuration < 0 ) {
853
-			throw new InvalidArgumentException( 'Fallback duration must be positive int but is: ' .
854
-				$fallbackBlockDuration );
849
+		if ($fallbackBlockDuration < 0) {
850
+			throw new InvalidArgumentException('Fallback duration must be positive int but is: '.
851
+				$fallbackBlockDuration);
855 852
 		}
856 853
 
857
-		$this->dataFactory->increment( 'wikibase.quality.constraints.sparql.throttling' );
858
-		$throttlingUntil = $this->getThrottling( $request );
859
-		if ( !( $throttlingUntil instanceof ConvertibleTimestamp ) ) {
860
-			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid( $request );
854
+		$this->dataFactory->increment('wikibase.quality.constraints.sparql.throttling');
855
+		$throttlingUntil = $this->getThrottling($request);
856
+		if (!($throttlingUntil instanceof ConvertibleTimestamp)) {
857
+			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid($request);
861 858
 			$this->throttlingLock->lock(
862 859
 				self::EXPIRY_LOCK_ID,
863
-				$this->getTimestampInFuture( new DateInterval( 'PT' . $fallbackBlockDuration . 'S' ) )
860
+				$this->getTimestampInFuture(new DateInterval('PT'.$fallbackBlockDuration.'S'))
864 861
 			);
865 862
 		} else {
866
-			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent( $throttlingUntil, $request );
867
-			$this->throttlingLock->lock( self::EXPIRY_LOCK_ID, $throttlingUntil );
863
+			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent($throttlingUntil, $request);
864
+			$this->throttlingLock->lock(self::EXPIRY_LOCK_ID, $throttlingUntil);
868 865
 		}
869 866
 		throw new TooManySparqlRequestsException();
870 867
 	}
Please login to merge, or discard this patch.
src/WikibaseQualityConstraintsHooks.php 1 patch
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -28,27 +28,27 @@  discard block
 block discarded – undo
28 28
 	/**
29 29
 	 * @param DatabaseUpdater $updater
30 30
 	 */
31
-	public static function onCreateSchema( DatabaseUpdater $updater ) {
32
-		$dir = dirname( __DIR__ ) . '/sql/';
31
+	public static function onCreateSchema(DatabaseUpdater $updater) {
32
+		$dir = dirname(__DIR__).'/sql/';
33 33
 
34 34
 		$updater->addExtensionTable(
35 35
 			'wbqc_constraints',
36
-			$dir . "/{$updater->getDB()->getType()}/tables-generated.sql"
36
+			$dir."/{$updater->getDB()->getType()}/tables-generated.sql"
37 37
 		);
38 38
 		$updater->addExtensionField(
39 39
 			'wbqc_constraints',
40 40
 			'constraint_id',
41
-			$dir . '/patch-wbqc_constraints-constraint_id.sql'
41
+			$dir.'/patch-wbqc_constraints-constraint_id.sql'
42 42
 		);
43 43
 		$updater->addExtensionIndex(
44 44
 			'wbqc_constraints',
45 45
 			'wbqc_constraints_guid_uniq',
46
-			$dir . '/patch-wbqc_constraints-wbqc_constraints_guid_uniq.sql'
46
+			$dir.'/patch-wbqc_constraints-wbqc_constraints_guid_uniq.sql'
47 47
 		);
48 48
 	}
49 49
 
50
-	public static function onWikibaseChange( Change $change ) {
51
-		if ( !( $change instanceof EntityChange ) ) {
50
+	public static function onWikibaseChange(Change $change) {
51
+		if (!($change instanceof EntityChange)) {
52 52
 			return;
53 53
 		}
54 54
 
@@ -57,48 +57,48 @@  discard block
 block discarded – undo
57 57
 
58 58
 		// If jobs are enabled and the results would be stored in some way run a job.
59 59
 		if (
60
-			$config->get( 'WBQualityConstraintsEnableConstraintsCheckJobs' ) &&
61
-			$config->get( 'WBQualityConstraintsCacheCheckConstraintsResults' ) &&
60
+			$config->get('WBQualityConstraintsEnableConstraintsCheckJobs') &&
61
+			$config->get('WBQualityConstraintsCacheCheckConstraintsResults') &&
62 62
 			self::isSelectedForJobRunBasedOnPercentage()
63 63
 		) {
64
-			$params = [ 'entityId' => $change->getEntityId()->getSerialization() ];
64
+			$params = ['entityId' => $change->getEntityId()->getSerialization()];
65 65
 			JobQueueGroup::singleton()->lazyPush(
66
-				new JobSpecification( CheckConstraintsJob::COMMAND, $params )
66
+				new JobSpecification(CheckConstraintsJob::COMMAND, $params)
67 67
 			);
68 68
 		}
69 69
 
70
-		if ( $config->get( 'WBQualityConstraintsEnableConstraintsImportFromStatements' ) &&
71
-			self::isConstraintStatementsChange( $config, $change )
70
+		if ($config->get('WBQualityConstraintsEnableConstraintsImportFromStatements') &&
71
+			self::isConstraintStatementsChange($config, $change)
72 72
 		) {
73
-			$params = [ 'propertyId' => $change->getEntityId()->getSerialization() ];
73
+			$params = ['propertyId' => $change->getEntityId()->getSerialization()];
74 74
 			$metadata = $change->getMetadata();
75
-			if ( array_key_exists( 'rev_id', $metadata ) ) {
75
+			if (array_key_exists('rev_id', $metadata)) {
76 76
 				$params['revisionId'] = $metadata['rev_id'];
77 77
 			}
78 78
 			JobQueueGroup::singleton()->push(
79
-				new JobSpecification( 'constraintsTableUpdate', $params )
79
+				new JobSpecification('constraintsTableUpdate', $params)
80 80
 			);
81 81
 		}
82 82
 	}
83 83
 
84 84
 	private static function isSelectedForJobRunBasedOnPercentage() {
85 85
 		$config = MediaWikiServices::getInstance()->getMainConfig();
86
-		$percentage = $config->get( 'WBQualityConstraintsEnableConstraintsCheckJobsRatio' );
86
+		$percentage = $config->get('WBQualityConstraintsEnableConstraintsCheckJobsRatio');
87 87
 
88
-		return mt_rand( 1, 100 ) <= $percentage;
88
+		return mt_rand(1, 100) <= $percentage;
89 89
 	}
90 90
 
91
-	public static function isConstraintStatementsChange( Config $config, Change $change ) {
92
-		if ( !( $change instanceof EntityChange ) ||
91
+	public static function isConstraintStatementsChange(Config $config, Change $change) {
92
+		if (!($change instanceof EntityChange) ||
93 93
 			 $change->getAction() !== EntityChange::UPDATE ||
94
-			 !( $change->getEntityId() instanceof PropertyId )
94
+			 !($change->getEntityId() instanceof PropertyId)
95 95
 		) {
96 96
 			return false;
97 97
 		}
98 98
 
99 99
 		$info = $change->getInfo();
100 100
 
101
-		if ( !array_key_exists( 'compactDiff', $info ) ) {
101
+		if (!array_key_exists('compactDiff', $info)) {
102 102
 			// the non-compact diff ($info['diff']) does not contain statement diffs (T110996),
103 103
 			// so we only know that the change *might* affect the constraint statements
104 104
 			return true;
@@ -107,47 +107,47 @@  discard block
 block discarded – undo
107 107
 		/** @var EntityDiffChangedAspects $aspects */
108 108
 		$aspects = $info['compactDiff'];
109 109
 
110
-		$propertyConstraintId = $config->get( 'WBQualityConstraintsPropertyConstraintId' );
111
-		return in_array( $propertyConstraintId, $aspects->getStatementChanges() );
110
+		$propertyConstraintId = $config->get('WBQualityConstraintsPropertyConstraintId');
111
+		return in_array($propertyConstraintId, $aspects->getStatementChanges());
112 112
 	}
113 113
 
114
-	public static function onArticlePurge( WikiPage $wikiPage ) {
114
+	public static function onArticlePurge(WikiPage $wikiPage) {
115 115
 		$repo = WikibaseRepo::getDefaultInstance();
116 116
 
117 117
 		$entityContentFactory = $repo->getEntityContentFactory();
118
-		if ( $entityContentFactory->isEntityContentModel( $wikiPage->getContentModel() ) ) {
118
+		if ($entityContentFactory->isEntityContentModel($wikiPage->getContentModel())) {
119 119
 			$entityIdLookup = $repo->getEntityIdLookup();
120
-			$entityId = $entityIdLookup->getEntityIdForTitle( $wikiPage->getTitle() );
121
-			if ( $entityId !== null ) {
120
+			$entityId = $entityIdLookup->getEntityIdForTitle($wikiPage->getTitle());
121
+			if ($entityId !== null) {
122 122
 				$resultsCache = ResultsCache::getDefaultInstance();
123
-				$resultsCache->delete( $entityId );
123
+				$resultsCache->delete($entityId);
124 124
 			}
125 125
 		}
126 126
 	}
127 127
 
128
-	public static function onBeforePageDisplay( OutputPage $out, Skin $skin ) {
128
+	public static function onBeforePageDisplay(OutputPage $out, Skin $skin) {
129 129
 		$repo = WikibaseRepo::getDefaultInstance();
130 130
 
131 131
 		$lookup = $repo->getEntityNamespaceLookup();
132 132
 		$title = $out->getTitle();
133
-		if ( $title === null ) {
133
+		if ($title === null) {
134 134
 			return;
135 135
 		}
136 136
 
137
-		if ( !$lookup->isNamespaceWithEntities( $title->getNamespace() ) ) {
137
+		if (!$lookup->isNamespaceWithEntities($title->getNamespace())) {
138 138
 			return;
139 139
 		}
140
-		if ( empty( $out->getJsConfigVars()['wbIsEditView'] ) ) {
140
+		if (empty($out->getJsConfigVars()['wbIsEditView'])) {
141 141
 			return;
142 142
 		}
143 143
 
144
-		$out->addModules( 'wikibase.quality.constraints.suggestions' );
144
+		$out->addModules('wikibase.quality.constraints.suggestions');
145 145
 
146
-		if ( !$out->getUser()->isRegistered() ) {
146
+		if (!$out->getUser()->isRegistered()) {
147 147
 			return;
148 148
 		}
149 149
 
150
-		$out->addModules( 'wikibase.quality.constraints.gadget' );
150
+		$out->addModules('wikibase.quality.constraints.gadget');
151 151
 	}
152 152
 
153 153
 }
Please login to merge, or discard this patch.
maintenance/ImportConstraintStatements.php 1 patch
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -11,10 +11,10 @@  discard block
 block discarded – undo
11 11
 use Wikimedia\Rdbms\ILBFactory;
12 12
 
13 13
 // @codeCoverageIgnoreStart
14
-$basePath = getenv( "MW_INSTALL_PATH" ) !== false
15
-	? getenv( "MW_INSTALL_PATH" ) : __DIR__ . "/../../..";
14
+$basePath = getenv("MW_INSTALL_PATH") !== false
15
+	? getenv("MW_INSTALL_PATH") : __DIR__."/../../..";
16 16
 
17
-require_once $basePath . "/maintenance/Maintenance.php";
17
+require_once $basePath."/maintenance/Maintenance.php";
18 18
 // @codeCoverageIgnoreEnd
19 19
 
20 20
 /**
@@ -46,20 +46,20 @@  discard block
 block discarded – undo
46 46
 
47 47
 	public function __construct() {
48 48
 		parent::__construct();
49
-		$this->newUpdateConstraintsTableJob = function ( $propertyIdSerialization ) {
49
+		$this->newUpdateConstraintsTableJob = function($propertyIdSerialization) {
50 50
 			return UpdateConstraintsTableJob::newFromGlobalState(
51 51
 				Title::newMainPage(),
52
-				[ 'propertyId' => $propertyIdSerialization ]
52
+				['propertyId' => $propertyIdSerialization]
53 53
 			);
54 54
 		};
55 55
 
56
-		$this->addDescription( 'Imports property constraints from statements on properties' );
57
-		$this->requireExtension( 'WikibaseQualityConstraints' );
58
-		$this->setBatchSize( 10 );
56
+		$this->addDescription('Imports property constraints from statements on properties');
57
+		$this->requireExtension('WikibaseQualityConstraints');
58
+		$this->setBatchSize(10);
59 59
 
60 60
 		// Wikibase classes are not yet loaded, so setup services in a callback run in execute
61 61
 		// that can be overridden in tests.
62
-		$this->setupServices = function () {
62
+		$this->setupServices = function() {
63 63
 			$repo = WikibaseRepo::getDefaultInstance();
64 64
 			$this->propertyInfoLookup = $repo->getStore()->getPropertyInfoLookup();
65 65
 			$this->lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
@@ -67,36 +67,36 @@  discard block
 block discarded – undo
67 67
 	}
68 68
 
69 69
 	public function execute() {
70
-		( $this->setupServices )();
71
-		if ( !$this->getConfig()->get( 'WBQualityConstraintsEnableConstraintsImportFromStatements' ) ) {
72
-			$this->error( 'Constraint statements are not enabled. Aborting.' );
70
+		($this->setupServices)();
71
+		if (!$this->getConfig()->get('WBQualityConstraintsEnableConstraintsImportFromStatements')) {
72
+			$this->error('Constraint statements are not enabled. Aborting.');
73 73
 			return;
74 74
 		}
75 75
 
76 76
 		$propertyInfos = $this->propertyInfoLookup->getAllPropertyInfo();
77
-		$propertyIds = array_keys( $propertyInfos );
77
+		$propertyIds = array_keys($propertyInfos);
78 78
 
79
-		foreach ( array_chunk( $propertyIds, $this->getBatchSize() ) as $propertyIdsChunk ) {
80
-			foreach ( $propertyIdsChunk as $propertyIdSerialization ) {
81
-				$this->output( sprintf(
79
+		foreach (array_chunk($propertyIds, $this->getBatchSize()) as $propertyIdsChunk) {
80
+			foreach ($propertyIdsChunk as $propertyIdSerialization) {
81
+				$this->output(sprintf(
82 82
 					'Importing constraint statements for % 6s... ',
83 83
 					$propertyIdSerialization ),
84 84
 					$propertyIdSerialization
85 85
 				);
86
-				$startTime = microtime( true );
87
-				$job = call_user_func( $this->newUpdateConstraintsTableJob, $propertyIdSerialization );
86
+				$startTime = microtime(true);
87
+				$job = call_user_func($this->newUpdateConstraintsTableJob, $propertyIdSerialization);
88 88
 				$job->run();
89
-				$endTime = microtime( true );
90
-				$millis = ( $endTime - $startTime ) * 1000;
91
-				$this->output( sprintf( 'done in % 6.2f ms.', $millis ), $propertyIdSerialization );
89
+				$endTime = microtime(true);
90
+				$millis = ($endTime - $startTime) * 1000;
91
+				$this->output(sprintf('done in % 6.2f ms.', $millis), $propertyIdSerialization);
92 92
 			}
93 93
 
94
-			$this->output( 'Waiting for replication... ', 'waitForReplication' );
95
-			$startTime = microtime( true );
94
+			$this->output('Waiting for replication... ', 'waitForReplication');
95
+			$startTime = microtime(true);
96 96
 			$this->lbFactory->waitForReplication();
97
-			$endTime = microtime( true );
98
-			$millis = ( $endTime - $startTime ) * 1000;
99
-			$this->output( sprintf( 'done in % 6.2f ms.', $millis ), 'waitForReplication' );
97
+			$endTime = microtime(true);
98
+			$millis = ($endTime - $startTime) * 1000;
99
+			$this->output(sprintf('done in % 6.2f ms.', $millis), 'waitForReplication');
100 100
 		}
101 101
 	}
102 102
 
Please login to merge, or discard this patch.
src/Job/UpdateConstraintsTableJob.php 1 patch
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -38,8 +38,8 @@  discard block
 block discarded – undo
38 38
 	 */
39 39
 	private const BATCH_SIZE = 50;
40 40
 
41
-	public static function newFromGlobalState( Title $title, array $params ) {
42
-		Assert::parameterType( 'string', $params['propertyId'], '$params["propertyId"]' );
41
+	public static function newFromGlobalState(Title $title, array $params) {
42
+		Assert::parameterType('string', $params['propertyId'], '$params["propertyId"]');
43 43
 		$services = MediaWikiServices::getInstance();
44 44
 		$repo = WikibaseRepo::getDefaultInstance();
45 45
 		return new UpdateConstraintsTableJob(
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 			$services->getMainConfig(),
51 51
 			ConstraintsServices::getConstraintStore(),
52 52
 			$services->getDBLoadBalancerFactory(),
53
-			$repo->getEntityRevisionLookup( Store::LOOKUP_CACHING_DISABLED ),
53
+			$repo->getEntityRevisionLookup(Store::LOOKUP_CACHING_DISABLED),
54 54
 			$repo->getBaseDataModelSerializerFactory()->newSnakSerializer()
55 55
 		);
56 56
 	}
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 		EntityRevisionLookup $entityRevisionLookup,
111 111
 		Serializer $snakSerializer
112 112
 	) {
113
-		parent::__construct( 'constraintsTableUpdate', $title, $params );
113
+		parent::__construct('constraintsTableUpdate', $title, $params);
114 114
 
115 115
 		$this->propertyId = $propertyId;
116 116
 		$this->revisionId = $revisionId;
@@ -121,11 +121,11 @@  discard block
 block discarded – undo
121 121
 		$this->snakSerializer = $snakSerializer;
122 122
 	}
123 123
 
124
-	public function extractParametersFromQualifiers( SnakList $qualifiers ) {
124
+	public function extractParametersFromQualifiers(SnakList $qualifiers) {
125 125
 		$parameters = [];
126
-		foreach ( $qualifiers as $qualifier ) {
126
+		foreach ($qualifiers as $qualifier) {
127 127
 			$qualifierId = $qualifier->getPropertyId()->getSerialization();
128
-			$paramSerialization = $this->snakSerializer->serialize( $qualifier );
128
+			$paramSerialization = $this->snakSerializer->serialize($qualifier);
129 129
 			$parameters[$qualifierId][] = $paramSerialization;
130 130
 		}
131 131
 		return $parameters;
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 		'@phan-var \Wikibase\DataModel\Entity\EntityIdValue $dataValue';
143 143
 		$entityId = $dataValue->getEntityId();
144 144
 		$constraintTypeQid = $entityId->getSerialization();
145
-		$parameters = $this->extractParametersFromQualifiers( $constraintStatement->getQualifiers() );
145
+		$parameters = $this->extractParametersFromQualifiers($constraintStatement->getQualifiers());
146 146
 		return new Constraint(
147 147
 			$constraintId,
148 148
 			$propertyId,
@@ -157,24 +157,24 @@  discard block
 block discarded – undo
157 157
 		PropertyId $propertyConstraintPropertyId
158 158
 	) {
159 159
 		$constraintsStatements = $property->getStatements()
160
-			->getByPropertyId( $propertyConstraintPropertyId )
161
-			->getByRank( [ Statement::RANK_PREFERRED, Statement::RANK_NORMAL ] );
160
+			->getByPropertyId($propertyConstraintPropertyId)
161
+			->getByRank([Statement::RANK_PREFERRED, Statement::RANK_NORMAL]);
162 162
 		$constraints = [];
163
-		foreach ( $constraintsStatements->getIterator() as $constraintStatement ) {
164
-			$constraints[] = $this->extractConstraintFromStatement( $property->getId(), $constraintStatement );
165
-			if ( count( $constraints ) >= self::BATCH_SIZE ) {
166
-				$constraintStore->insertBatch( $constraints );
163
+		foreach ($constraintsStatements->getIterator() as $constraintStatement) {
164
+			$constraints[] = $this->extractConstraintFromStatement($property->getId(), $constraintStatement);
165
+			if (count($constraints) >= self::BATCH_SIZE) {
166
+				$constraintStore->insertBatch($constraints);
167 167
 				// interrupt transaction and wait for replication
168
-				$connection = $this->lbFactory->getMainLB()->getConnection( DB_MASTER );
169
-				$connection->endAtomic( __CLASS__ );
170
-				if ( !$connection->explicitTrxActive() ) {
168
+				$connection = $this->lbFactory->getMainLB()->getConnection(DB_MASTER);
169
+				$connection->endAtomic(__CLASS__);
170
+				if (!$connection->explicitTrxActive()) {
171 171
 					$this->lbFactory->waitForReplication();
172 172
 				}
173
-				$connection->startAtomic( __CLASS__ );
173
+				$connection->startAtomic(__CLASS__);
174 174
 				$constraints = [];
175 175
 			}
176 176
 		}
177
-		$constraintStore->insertBatch( $constraints );
177
+		$constraintStore->insertBatch($constraints);
178 178
 	}
179 179
 
180 180
 	/**
@@ -185,24 +185,24 @@  discard block
 block discarded – undo
185 185
 	public function run() {
186 186
 		// TODO in the future: only touch constraints affected by the edit (requires T163465)
187 187
 
188
-		$propertyId = new PropertyId( $this->propertyId );
188
+		$propertyId = new PropertyId($this->propertyId);
189 189
 		$propertyRevision = $this->entityRevisionLookup->getEntityRevision(
190 190
 			$propertyId,
191 191
 			0, // latest
192 192
 			LookupConstants::LATEST_FROM_REPLICA
193 193
 		);
194 194
 
195
-		if ( $this->revisionId !== null && $propertyRevision->getRevisionId() < $this->revisionId ) {
196
-			JobQueueGroup::singleton()->push( $this );
195
+		if ($this->revisionId !== null && $propertyRevision->getRevisionId() < $this->revisionId) {
196
+			JobQueueGroup::singleton()->push($this);
197 197
 			return true;
198 198
 		}
199 199
 
200
-		$connection = $this->lbFactory->getMainLB()->getConnection( DB_MASTER );
200
+		$connection = $this->lbFactory->getMainLB()->getConnection(DB_MASTER);
201 201
 		// start transaction (if not started yet) – using __CLASS__, not __METHOD__,
202 202
 		// because importConstraintsForProperty() can interrupt the transaction
203
-		$connection->startAtomic( __CLASS__ );
203
+		$connection->startAtomic(__CLASS__);
204 204
 
205
-		$this->constraintStore->deleteForProperty( $propertyId );
205
+		$this->constraintStore->deleteForProperty($propertyId);
206 206
 
207 207
 		/** @var Property $property */
208 208
 		$property = $propertyRevision->getEntity();
@@ -210,10 +210,10 @@  discard block
 block discarded – undo
210 210
 		$this->importConstraintsForProperty(
211 211
 			$property,
212 212
 			$this->constraintStore,
213
-			new PropertyId( $this->config->get( 'WBQualityConstraintsPropertyConstraintId' ) )
213
+			new PropertyId($this->config->get('WBQualityConstraintsPropertyConstraintId'))
214 214
 		);
215 215
 
216
-		$connection->endAtomic( __CLASS__ );
216
+		$connection->endAtomic(__CLASS__);
217 217
 
218 218
 		return true;
219 219
 	}
Please login to merge, or discard this patch.