@@ -25,7 +25,7 @@ discard block |
||
25 | 25 | * then using the main DBLoadBalancer service may be incorrect. |
26 | 26 | * @param string|false $dbName Database name ($domain for ILoadBalancer methods). |
27 | 27 | */ |
28 | - public function __construct( ILoadBalancer $lb, $dbName ) { |
|
28 | + public function __construct(ILoadBalancer $lb, $dbName) { |
|
29 | 29 | $this->lb = $lb; |
30 | 30 | $this->dbName = $dbName; |
31 | 31 | } |
@@ -35,17 +35,17 @@ discard block |
||
35 | 35 | * |
36 | 36 | * @return Constraint[] |
37 | 37 | */ |
38 | - public function queryConstraintsForProperty( PropertyId $propertyId ) { |
|
39 | - $dbr = $this->lb->getConnectionRef( ILoadBalancer::DB_REPLICA, [], $this->dbName ); |
|
38 | + public function queryConstraintsForProperty(PropertyId $propertyId) { |
|
39 | + $dbr = $this->lb->getConnectionRef(ILoadBalancer::DB_REPLICA, [], $this->dbName); |
|
40 | 40 | |
41 | 41 | $results = $dbr->select( |
42 | 42 | 'wbqc_constraints', |
43 | 43 | '*', |
44 | - [ 'pid' => $propertyId->getNumericId() ], |
|
44 | + ['pid' => $propertyId->getNumericId()], |
|
45 | 45 | __METHOD__ |
46 | 46 | ); |
47 | 47 | |
48 | - return $this->convertToConstraints( $results ); |
|
48 | + return $this->convertToConstraints($results); |
|
49 | 49 | } |
50 | 50 | |
51 | 51 | /** |
@@ -53,26 +53,26 @@ discard block |
||
53 | 53 | * |
54 | 54 | * @return Constraint[] |
55 | 55 | */ |
56 | - private function convertToConstraints( IResultWrapper $results ) { |
|
56 | + private function convertToConstraints(IResultWrapper $results) { |
|
57 | 57 | $constraints = []; |
58 | - $logger = LoggerFactory::getInstance( 'WikibaseQualityConstraints' ); |
|
59 | - foreach ( $results as $result ) { |
|
58 | + $logger = LoggerFactory::getInstance('WikibaseQualityConstraints'); |
|
59 | + foreach ($results as $result) { |
|
60 | 60 | $constraintTypeItemId = $result->constraint_type_qid; |
61 | - $constraintParameters = json_decode( $result->constraint_parameters, true ); |
|
61 | + $constraintParameters = json_decode($result->constraint_parameters, true); |
|
62 | 62 | |
63 | - if ( $constraintParameters === null ) { |
|
63 | + if ($constraintParameters === null) { |
|
64 | 64 | // T171295 |
65 | - $logger->warning( 'Constraint {constraintId} has invalid constraint parameters.', [ |
|
65 | + $logger->warning('Constraint {constraintId} has invalid constraint parameters.', [ |
|
66 | 66 | 'method' => __METHOD__, |
67 | 67 | 'constraintId' => $result->constraint_guid, |
68 | 68 | 'constraintParameters' => $result->constraint_parameters, |
69 | - ] ); |
|
70 | - $constraintParameters = [ '@error' => [ /* unknown */ ] ]; |
|
69 | + ]); |
|
70 | + $constraintParameters = ['@error' => [/* unknown */]]; |
|
71 | 71 | } |
72 | 72 | |
73 | 73 | $constraints[] = new Constraint( |
74 | 74 | $result->constraint_guid, |
75 | - PropertyId::newFromNumber( $result->pid ), |
|
75 | + PropertyId::newFromNumber($result->pid), |
|
76 | 76 | $constraintTypeItemId, |
77 | 77 | $constraintParameters |
78 | 78 | ); |
@@ -17,10 +17,10 @@ discard block |
||
17 | 17 | use Wikibase\Repo\WikibaseRepo; |
18 | 18 | |
19 | 19 | // @codeCoverageIgnoreStart |
20 | -$basePath = getenv( "MW_INSTALL_PATH" ) !== false |
|
21 | - ? getenv( "MW_INSTALL_PATH" ) : __DIR__ . "/../../.."; |
|
20 | +$basePath = getenv("MW_INSTALL_PATH") !== false |
|
21 | + ? getenv("MW_INSTALL_PATH") : __DIR__."/../../.."; |
|
22 | 22 | |
23 | -require_once $basePath . "/maintenance/Maintenance.php"; |
|
23 | +require_once $basePath."/maintenance/Maintenance.php"; |
|
24 | 24 | // @codeCoverageIgnoreEnd |
25 | 25 | |
26 | 26 | /** |
@@ -59,20 +59,20 @@ discard block |
||
59 | 59 | parent::__construct(); |
60 | 60 | |
61 | 61 | $this->addDescription( |
62 | - 'Import entities needed for constraint checks ' . |
|
62 | + 'Import entities needed for constraint checks '. |
|
63 | 63 | 'from Wikidata into the local repository.' |
64 | 64 | ); |
65 | 65 | $this->addOption( |
66 | 66 | 'config-format', |
67 | - 'The format in which the resulting configuration will be omitted: ' . |
|
68 | - '"globals" for directly settings global variables, suitable for inclusion in LocalSettings.php (default), ' . |
|
67 | + 'The format in which the resulting configuration will be omitted: '. |
|
68 | + '"globals" for directly settings global variables, suitable for inclusion in LocalSettings.php (default), '. |
|
69 | 69 | 'or "wgConf" for printing parts of arrays suitable for inclusion in $wgConf->settings.' |
70 | 70 | ); |
71 | 71 | $this->addOption( |
72 | 72 | 'dry-run', |
73 | 73 | 'Don’t actually import entities, just print which ones would be imported.' |
74 | 74 | ); |
75 | - $this->requireExtension( 'WikibaseQualityConstraints' ); |
|
75 | + $this->requireExtension('WikibaseQualityConstraints'); |
|
76 | 76 | } |
77 | 77 | |
78 | 78 | /** |
@@ -84,8 +84,8 @@ discard block |
||
84 | 84 | $this->entityDeserializer = $repo->getInternalFormatEntityDeserializer(); |
85 | 85 | $this->entityStore = $repo->getEntityStore(); |
86 | 86 | $this->httpRequestFactory = MediaWikiServices::getInstance()->getHttpRequestFactory(); |
87 | - if ( !$this->getOption( 'dry-run', false ) ) { |
|
88 | - $this->user = User::newSystemUser( 'WikibaseQualityConstraints importer' ); |
|
87 | + if (!$this->getOption('dry-run', false)) { |
|
88 | + $this->user = User::newSystemUser('WikibaseQualityConstraints importer'); |
|
89 | 89 | } |
90 | 90 | } |
91 | 91 | |
@@ -94,21 +94,21 @@ discard block |
||
94 | 94 | |
95 | 95 | $configUpdates = []; |
96 | 96 | |
97 | - $extensionJsonFile = __DIR__ . '/../extension.json'; |
|
98 | - $extensionJsonText = file_get_contents( $extensionJsonFile ); |
|
99 | - $extensionJson = json_decode( $extensionJsonText, /* assoc = */ true ); |
|
97 | + $extensionJsonFile = __DIR__.'/../extension.json'; |
|
98 | + $extensionJsonText = file_get_contents($extensionJsonFile); |
|
99 | + $extensionJson = json_decode($extensionJsonText, /* assoc = */ true); |
|
100 | 100 | // @phan-suppress-next-line PhanTypeArraySuspiciousNullable |
101 | - $wikidataEntityIds = $this->getEntitiesToImport( $extensionJson['config'], $this->getConfig() ); |
|
101 | + $wikidataEntityIds = $this->getEntitiesToImport($extensionJson['config'], $this->getConfig()); |
|
102 | 102 | |
103 | - foreach ( $wikidataEntityIds as $key => $wikidataEntityId ) { |
|
104 | - $localEntityId = $this->importEntityFromWikidata( $wikidataEntityId ); |
|
103 | + foreach ($wikidataEntityIds as $key => $wikidataEntityId) { |
|
104 | + $localEntityId = $this->importEntityFromWikidata($wikidataEntityId); |
|
105 | 105 | $configUpdates[$key] = [ |
106 | 106 | 'wikidata' => $wikidataEntityId, |
107 | 107 | 'local' => $localEntityId, |
108 | 108 | ]; |
109 | 109 | } |
110 | 110 | |
111 | - $this->outputConfigUpdates( $configUpdates ); |
|
111 | + $this->outputConfigUpdates($configUpdates); |
|
112 | 112 | } |
113 | 113 | |
114 | 114 | /** |
@@ -116,18 +116,18 @@ discard block |
||
116 | 116 | * @param Config $wikiConfig |
117 | 117 | * @return string[] |
118 | 118 | */ |
119 | - private function getEntitiesToImport( array $extensionJsonConfig, Config $wikiConfig ) { |
|
119 | + private function getEntitiesToImport(array $extensionJsonConfig, Config $wikiConfig) { |
|
120 | 120 | $wikidataEntityIds = []; |
121 | 121 | |
122 | - foreach ( $extensionJsonConfig as $key => $value ) { |
|
123 | - if ( !preg_match( '/Id$/', $key ) ) { |
|
122 | + foreach ($extensionJsonConfig as $key => $value) { |
|
123 | + if (!preg_match('/Id$/', $key)) { |
|
124 | 124 | continue; |
125 | 125 | } |
126 | 126 | |
127 | 127 | $wikidataEntityId = $value['value']; |
128 | - $localEntityId = $wikiConfig->get( $key ); |
|
128 | + $localEntityId = $wikiConfig->get($key); |
|
129 | 129 | |
130 | - if ( $localEntityId === $wikidataEntityId ) { |
|
130 | + if ($localEntityId === $wikidataEntityId) { |
|
131 | 131 | $wikidataEntityIds[$key] = $wikidataEntityId; |
132 | 132 | } |
133 | 133 | } |
@@ -139,10 +139,10 @@ discard block |
||
139 | 139 | * @param string $wikidataEntityId |
140 | 140 | * @return string local entity ID |
141 | 141 | */ |
142 | - private function importEntityFromWikidata( $wikidataEntityId ) { |
|
142 | + private function importEntityFromWikidata($wikidataEntityId) { |
|
143 | 143 | $wikidataEntityUrl = "https://www.wikidata.org/wiki/Special:EntityData/$wikidataEntityId.json"; |
144 | - $wikidataEntitiesJson = $this->httpRequestFactory->get( $wikidataEntityUrl, [], __METHOD__ ); |
|
145 | - return $this->importEntityFromJson( $wikidataEntityId, $wikidataEntitiesJson ); |
|
144 | + $wikidataEntitiesJson = $this->httpRequestFactory->get($wikidataEntityUrl, [], __METHOD__); |
|
145 | + return $this->importEntityFromJson($wikidataEntityId, $wikidataEntitiesJson); |
|
146 | 146 | } |
147 | 147 | |
148 | 148 | /** |
@@ -150,24 +150,24 @@ discard block |
||
150 | 150 | * @param string $wikidataEntitiesJson |
151 | 151 | * @return string local entity ID |
152 | 152 | */ |
153 | - private function importEntityFromJson( $wikidataEntityId, $wikidataEntitiesJson ) { |
|
153 | + private function importEntityFromJson($wikidataEntityId, $wikidataEntitiesJson) { |
|
154 | 154 | // @phan-suppress-next-line PhanTypeArraySuspiciousNullable |
155 | - $wikidataEntityArray = json_decode( $wikidataEntitiesJson, true )['entities'][$wikidataEntityId]; |
|
156 | - $wikidataEntity = $this->entityDeserializer->deserialize( $wikidataEntityArray ); |
|
155 | + $wikidataEntityArray = json_decode($wikidataEntitiesJson, true)['entities'][$wikidataEntityId]; |
|
156 | + $wikidataEntity = $this->entityDeserializer->deserialize($wikidataEntityArray); |
|
157 | 157 | |
158 | - $wikidataEntity->setId( null ); |
|
158 | + $wikidataEntity->setId(null); |
|
159 | 159 | |
160 | - if ( $wikidataEntity instanceof StatementListProvider ) { |
|
160 | + if ($wikidataEntity instanceof StatementListProvider) { |
|
161 | 161 | $wikidataEntity->getStatements()->clear(); |
162 | 162 | } |
163 | 163 | |
164 | - if ( $wikidataEntity instanceof Item ) { |
|
165 | - $wikidataEntity->setSiteLinkList( new SiteLinkList() ); |
|
164 | + if ($wikidataEntity instanceof Item) { |
|
165 | + $wikidataEntity->setSiteLinkList(new SiteLinkList()); |
|
166 | 166 | } |
167 | 167 | |
168 | - if ( $this->getOption( 'dry-run', false ) ) { |
|
169 | - $wikidataEntityJson = json_encode( $this->entitySerializer->serialize( $wikidataEntity ) ); |
|
170 | - $this->output( $wikidataEntityJson . "\n" ); |
|
168 | + if ($this->getOption('dry-run', false)) { |
|
169 | + $wikidataEntityJson = json_encode($this->entitySerializer->serialize($wikidataEntity)); |
|
170 | + $this->output($wikidataEntityJson."\n"); |
|
171 | 171 | return "-$wikidataEntityId"; |
172 | 172 | } |
173 | 173 | |
@@ -180,12 +180,12 @@ discard block |
||
180 | 180 | )->getEntity(); |
181 | 181 | |
182 | 182 | return $localEntity->getId()->getSerialization(); |
183 | - } catch ( StorageException $storageException ) { |
|
184 | - return $this->storageExceptionToEntityId( $storageException ); |
|
183 | + } catch (StorageException $storageException) { |
|
184 | + return $this->storageExceptionToEntityId($storageException); |
|
185 | 185 | } |
186 | 186 | } |
187 | 187 | |
188 | - private function storageExceptionToEntityId( StorageException $storageException ) { |
|
188 | + private function storageExceptionToEntityId(StorageException $storageException) { |
|
189 | 189 | $message = $storageException->getMessage(); |
190 | 190 | // example messages: |
191 | 191 | // * Item [[Item:Q475|Q475]] already has label "as references" |
@@ -195,25 +195,25 @@ discard block |
||
195 | 195 | // * Property [[Property:P694|P694]] already has label "instance of" |
196 | 196 | // associated with language code en. |
197 | 197 | $pattern = '/[[|]([^][|]*)]] already has label .* associated with language code/'; |
198 | - if ( preg_match( $pattern, $message, $matches ) ) { |
|
198 | + if (preg_match($pattern, $message, $matches)) { |
|
199 | 199 | return $matches[1]; |
200 | 200 | } else { |
201 | 201 | throw $storageException; |
202 | 202 | } |
203 | 203 | } |
204 | 204 | |
205 | - private function outputConfigUpdates( array $configUpdates ) { |
|
206 | - $configFormat = $this->getOption( 'config-format', 'globals' ); |
|
207 | - switch ( $configFormat ) { |
|
205 | + private function outputConfigUpdates(array $configUpdates) { |
|
206 | + $configFormat = $this->getOption('config-format', 'globals'); |
|
207 | + switch ($configFormat) { |
|
208 | 208 | case 'globals': |
209 | - $this->outputConfigUpdatesGlobals( $configUpdates ); |
|
209 | + $this->outputConfigUpdatesGlobals($configUpdates); |
|
210 | 210 | break; |
211 | 211 | case 'wgConf': |
212 | - $this->outputConfigUpdatesWgConf( $configUpdates ); |
|
212 | + $this->outputConfigUpdatesWgConf($configUpdates); |
|
213 | 213 | break; |
214 | 214 | default: |
215 | - $this->error( "Invalid config format \"$configFormat\", using \"globals\"" ); |
|
216 | - $this->outputConfigUpdatesGlobals( $configUpdates ); |
|
215 | + $this->error("Invalid config format \"$configFormat\", using \"globals\""); |
|
216 | + $this->outputConfigUpdatesGlobals($configUpdates); |
|
217 | 217 | break; |
218 | 218 | } |
219 | 219 | } |
@@ -221,22 +221,22 @@ discard block |
||
221 | 221 | /** |
222 | 222 | * @param array[] $configUpdates |
223 | 223 | */ |
224 | - private function outputConfigUpdatesGlobals( array $configUpdates ) { |
|
225 | - foreach ( $configUpdates as $key => $value ) { |
|
226 | - $localValueCode = var_export( $value['local'], true ); |
|
227 | - $this->output( "\$wg$key = $localValueCode;\n" ); |
|
224 | + private function outputConfigUpdatesGlobals(array $configUpdates) { |
|
225 | + foreach ($configUpdates as $key => $value) { |
|
226 | + $localValueCode = var_export($value['local'], true); |
|
227 | + $this->output("\$wg$key = $localValueCode;\n"); |
|
228 | 228 | } |
229 | 229 | } |
230 | 230 | |
231 | 231 | /** |
232 | 232 | * @param array[] $configUpdates |
233 | 233 | */ |
234 | - private function outputConfigUpdatesWgConf( array $configUpdates ) { |
|
235 | - foreach ( $configUpdates as $key => $value ) { |
|
236 | - $keyCode = var_export( "wg$key", true ); |
|
237 | - $wikidataValueCode = var_export( $value['wikidata'], true ); |
|
238 | - $localValueCode = var_export( $value['local'], true ); |
|
239 | - $wikiIdCode = var_export( wfWikiID(), true ); |
|
234 | + private function outputConfigUpdatesWgConf(array $configUpdates) { |
|
235 | + foreach ($configUpdates as $key => $value) { |
|
236 | + $keyCode = var_export("wg$key", true); |
|
237 | + $wikidataValueCode = var_export($value['wikidata'], true); |
|
238 | + $localValueCode = var_export($value['local'], true); |
|
239 | + $wikiIdCode = var_export(wfWikiID(), true); |
|
240 | 240 | $block = <<< EOF |
241 | 241 | $keyCode => [ |
242 | 242 | 'default' => $wikidataValueCode, |
@@ -245,7 +245,7 @@ discard block |
||
245 | 245 | |
246 | 246 | |
247 | 247 | EOF; |
248 | - $this->output( $block ); |
|
248 | + $this->output($block); |
|
249 | 249 | } |
250 | 250 | } |
251 | 251 |
@@ -8,19 +8,19 @@ |
||
8 | 8 | use Wikibase\Repo\WikibaseRepo; |
9 | 9 | |
10 | 10 | return [ |
11 | - WikibaseServices::ENTITY_LOOKUP => function( MediaWikiServices $services ) { |
|
11 | + WikibaseServices::ENTITY_LOOKUP => function(MediaWikiServices $services) { |
|
12 | 12 | return new ExceptionIgnoringEntityLookup( |
13 | 13 | WikibaseRepo::getDefaultInstance()->getEntityLookup() |
14 | 14 | ); |
15 | 15 | }, |
16 | 16 | |
17 | - WikibaseServices::ENTITY_LOOKUP_WITHOUT_CACHE => function( MediaWikiServices $services ) { |
|
17 | + WikibaseServices::ENTITY_LOOKUP_WITHOUT_CACHE => function(MediaWikiServices $services) { |
|
18 | 18 | return new ExceptionIgnoringEntityLookup( |
19 | - WikibaseRepo::getDefaultInstance()->getEntityLookup( Store::LOOKUP_CACHING_RETRIEVE_ONLY ) |
|
19 | + WikibaseRepo::getDefaultInstance()->getEntityLookup(Store::LOOKUP_CACHING_RETRIEVE_ONLY) |
|
20 | 20 | ); |
21 | 21 | }, |
22 | 22 | |
23 | - WikibaseServices::PROPERTY_DATA_TYPE_LOOKUP => function( MediaWikiServices $services ) { |
|
23 | + WikibaseServices::PROPERTY_DATA_TYPE_LOOKUP => function(MediaWikiServices $services) { |
|
24 | 24 | return WikibaseRepo::getDefaultInstance()->getPropertyDataTypeLookup(); |
25 | 25 | }, |
26 | 26 | ]; |
@@ -28,25 +28,25 @@ discard block |
||
28 | 28 | /** |
29 | 29 | * @param DatabaseUpdater $updater |
30 | 30 | */ |
31 | - public static function onCreateSchema( DatabaseUpdater $updater ) { |
|
31 | + public static function onCreateSchema(DatabaseUpdater $updater) { |
|
32 | 32 | $updater->addExtensionTable( |
33 | 33 | 'wbqc_constraints', |
34 | - __DIR__ . '/../sql/create_wbqc_constraints.sql' |
|
34 | + __DIR__.'/../sql/create_wbqc_constraints.sql' |
|
35 | 35 | ); |
36 | 36 | $updater->addExtensionField( |
37 | 37 | 'wbqc_constraints', |
38 | 38 | 'constraint_id', |
39 | - __DIR__ . '/../sql/patch-wbqc_constraints-constraint_id.sql' |
|
39 | + __DIR__.'/../sql/patch-wbqc_constraints-constraint_id.sql' |
|
40 | 40 | ); |
41 | 41 | $updater->addExtensionIndex( |
42 | 42 | 'wbqc_constraints', |
43 | 43 | 'wbqc_constraints_guid_uniq', |
44 | - __DIR__ . '/../sql/patch-wbqc_constraints-wbqc_constraints_guid_uniq.sql' |
|
44 | + __DIR__.'/../sql/patch-wbqc_constraints-wbqc_constraints_guid_uniq.sql' |
|
45 | 45 | ); |
46 | 46 | } |
47 | 47 | |
48 | - public static function onWikibaseChange( Change $change ) { |
|
49 | - if ( !( $change instanceof EntityChange ) ) { |
|
48 | + public static function onWikibaseChange(Change $change) { |
|
49 | + if (!($change instanceof EntityChange)) { |
|
50 | 50 | return; |
51 | 51 | } |
52 | 52 | |
@@ -55,48 +55,48 @@ discard block |
||
55 | 55 | |
56 | 56 | // If jobs are enabled and the results would be stored in some way run a job. |
57 | 57 | if ( |
58 | - $config->get( 'WBQualityConstraintsEnableConstraintsCheckJobs' ) && |
|
59 | - $config->get( 'WBQualityConstraintsCacheCheckConstraintsResults' ) && |
|
58 | + $config->get('WBQualityConstraintsEnableConstraintsCheckJobs') && |
|
59 | + $config->get('WBQualityConstraintsCacheCheckConstraintsResults') && |
|
60 | 60 | self::isSelectedForJobRunBasedOnPercentage() |
61 | 61 | ) { |
62 | - $params = [ 'entityId' => $change->getEntityId()->getSerialization() ]; |
|
62 | + $params = ['entityId' => $change->getEntityId()->getSerialization()]; |
|
63 | 63 | JobQueueGroup::singleton()->push( |
64 | - new JobSpecification( CheckConstraintsJob::COMMAND, $params ) |
|
64 | + new JobSpecification(CheckConstraintsJob::COMMAND, $params) |
|
65 | 65 | ); |
66 | 66 | } |
67 | 67 | |
68 | - if ( $config->get( 'WBQualityConstraintsEnableConstraintsImportFromStatements' ) && |
|
69 | - self::isConstraintStatementsChange( $config, $change ) |
|
68 | + if ($config->get('WBQualityConstraintsEnableConstraintsImportFromStatements') && |
|
69 | + self::isConstraintStatementsChange($config, $change) |
|
70 | 70 | ) { |
71 | - $params = [ 'propertyId' => $change->getEntityId()->getSerialization() ]; |
|
71 | + $params = ['propertyId' => $change->getEntityId()->getSerialization()]; |
|
72 | 72 | $metadata = $change->getMetadata(); |
73 | - if ( array_key_exists( 'rev_id', $metadata ) ) { |
|
73 | + if (array_key_exists('rev_id', $metadata)) { |
|
74 | 74 | $params['revisionId'] = $metadata['rev_id']; |
75 | 75 | } |
76 | 76 | JobQueueGroup::singleton()->push( |
77 | - new JobSpecification( 'constraintsTableUpdate', $params ) |
|
77 | + new JobSpecification('constraintsTableUpdate', $params) |
|
78 | 78 | ); |
79 | 79 | } |
80 | 80 | } |
81 | 81 | |
82 | 82 | private static function isSelectedForJobRunBasedOnPercentage() { |
83 | 83 | $config = MediaWikiServices::getInstance()->getMainConfig(); |
84 | - $percentage = $config->get( 'WBQualityConstraintsEnableConstraintsCheckJobsRatio' ); |
|
84 | + $percentage = $config->get('WBQualityConstraintsEnableConstraintsCheckJobsRatio'); |
|
85 | 85 | |
86 | - return mt_rand( 1, 100 ) <= $percentage; |
|
86 | + return mt_rand(1, 100) <= $percentage; |
|
87 | 87 | } |
88 | 88 | |
89 | - public static function isConstraintStatementsChange( Config $config, Change $change ) { |
|
90 | - if ( !( $change instanceof EntityChange ) || |
|
89 | + public static function isConstraintStatementsChange(Config $config, Change $change) { |
|
90 | + if (!($change instanceof EntityChange) || |
|
91 | 91 | $change->getAction() !== EntityChange::UPDATE || |
92 | - !( $change->getEntityId() instanceof PropertyId ) |
|
92 | + !($change->getEntityId() instanceof PropertyId) |
|
93 | 93 | ) { |
94 | 94 | return false; |
95 | 95 | } |
96 | 96 | |
97 | 97 | $info = $change->getInfo(); |
98 | 98 | |
99 | - if ( !array_key_exists( 'compactDiff', $info ) ) { |
|
99 | + if (!array_key_exists('compactDiff', $info)) { |
|
100 | 100 | // the non-compact diff ($info['diff']) does not contain statement diffs (T110996), |
101 | 101 | // so we only know that the change *might* affect the constraint statements |
102 | 102 | return true; |
@@ -105,47 +105,47 @@ discard block |
||
105 | 105 | /** @var EntityDiffChangedAspects $aspects */ |
106 | 106 | $aspects = $info['compactDiff']; |
107 | 107 | |
108 | - $propertyConstraintId = $config->get( 'WBQualityConstraintsPropertyConstraintId' ); |
|
109 | - return in_array( $propertyConstraintId, $aspects->getStatementChanges() ); |
|
108 | + $propertyConstraintId = $config->get('WBQualityConstraintsPropertyConstraintId'); |
|
109 | + return in_array($propertyConstraintId, $aspects->getStatementChanges()); |
|
110 | 110 | } |
111 | 111 | |
112 | - public static function onArticlePurge( WikiPage $wikiPage ) { |
|
112 | + public static function onArticlePurge(WikiPage $wikiPage) { |
|
113 | 113 | $repo = WikibaseRepo::getDefaultInstance(); |
114 | 114 | |
115 | 115 | $entityContentFactory = $repo->getEntityContentFactory(); |
116 | - if ( $entityContentFactory->isEntityContentModel( $wikiPage->getContentModel() ) ) { |
|
116 | + if ($entityContentFactory->isEntityContentModel($wikiPage->getContentModel())) { |
|
117 | 117 | $entityIdLookup = $repo->getEntityIdLookup(); |
118 | - $entityId = $entityIdLookup->getEntityIdForTitle( $wikiPage->getTitle() ); |
|
119 | - if ( $entityId !== null ) { |
|
118 | + $entityId = $entityIdLookup->getEntityIdForTitle($wikiPage->getTitle()); |
|
119 | + if ($entityId !== null) { |
|
120 | 120 | $resultsCache = ResultsCache::getDefaultInstance(); |
121 | - $resultsCache->delete( $entityId ); |
|
121 | + $resultsCache->delete($entityId); |
|
122 | 122 | } |
123 | 123 | } |
124 | 124 | } |
125 | 125 | |
126 | - public static function onBeforePageDisplay( OutputPage $out, Skin $skin ) { |
|
126 | + public static function onBeforePageDisplay(OutputPage $out, Skin $skin) { |
|
127 | 127 | $repo = WikibaseRepo::getDefaultInstance(); |
128 | 128 | |
129 | 129 | $lookup = $repo->getEntityNamespaceLookup(); |
130 | 130 | $title = $out->getTitle(); |
131 | - if ( $title === null ) { |
|
131 | + if ($title === null) { |
|
132 | 132 | return; |
133 | 133 | } |
134 | 134 | |
135 | - if ( !$lookup->isNamespaceWithEntities( $title->getNamespace() ) ) { |
|
135 | + if (!$lookup->isNamespaceWithEntities($title->getNamespace())) { |
|
136 | 136 | return; |
137 | 137 | } |
138 | - if ( empty( $out->getJsConfigVars()['wbIsEditView'] ) ) { |
|
138 | + if (empty($out->getJsConfigVars()['wbIsEditView'])) { |
|
139 | 139 | return; |
140 | 140 | } |
141 | 141 | |
142 | - $out->addModules( 'wikibase.quality.constraints.suggestions' ); |
|
142 | + $out->addModules('wikibase.quality.constraints.suggestions'); |
|
143 | 143 | |
144 | - if ( !$out->getUser()->isLoggedIn() ) { |
|
144 | + if (!$out->getUser()->isLoggedIn()) { |
|
145 | 145 | return; |
146 | 146 | } |
147 | 147 | |
148 | - $out->addModules( 'wikibase.quality.constraints.gadget' ); |
|
148 | + $out->addModules('wikibase.quality.constraints.gadget'); |
|
149 | 149 | } |
150 | 150 | |
151 | 151 | } |
@@ -163,58 +163,58 @@ discard block |
||
163 | 163 | $this->defaultUserAgent = $defaultUserAgent; |
164 | 164 | $this->requestFactory = $requestFactory; |
165 | 165 | $this->entityPrefixes = []; |
166 | - foreach ( $rdfVocabulary->entityNamespaceNames as $namespaceName ) { |
|
167 | - $this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI( $namespaceName ); |
|
166 | + foreach ($rdfVocabulary->entityNamespaceNames as $namespaceName) { |
|
167 | + $this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI($namespaceName); |
|
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 ) { |
|
173 | + private function getQueryPrefixes(RdfVocabulary $rdfVocabulary) { |
|
174 | 174 | // TODO: it would probably be smarter that RdfVocubulary 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 | $prefixes .= <<<END |
182 | -PREFIX wds: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_STATEMENT )}> |
|
183 | -PREFIX wdv: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_VALUE )}>\n |
|
182 | +PREFIX wds: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_STATEMENT)}> |
|
183 | +PREFIX wdv: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_VALUE)}>\n |
|
184 | 184 | END; |
185 | 185 | |
186 | - foreach ( $rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces ) { |
|
186 | + foreach ($rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces) { |
|
187 | 187 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_DIRECT_CLAIM]; |
188 | 188 | $prefixes .= <<<END |
189 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
189 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
190 | 190 | END; |
191 | 191 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM]; |
192 | 192 | $prefixes .= <<<END |
193 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
193 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
194 | 194 | END; |
195 | 195 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM_STATEMENT]; |
196 | 196 | $prefixes .= <<<END |
197 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
197 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
198 | 198 | END; |
199 | 199 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER]; |
200 | 200 | $prefixes .= <<<END |
201 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
201 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
202 | 202 | END; |
203 | 203 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER_VALUE]; |
204 | 204 | $prefixes .= <<<END |
205 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
205 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
206 | 206 | END; |
207 | 207 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE]; |
208 | 208 | $prefixes .= <<<END |
209 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
209 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
210 | 210 | END; |
211 | 211 | $namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE_VALUE]; |
212 | 212 | $prefixes .= <<<END |
213 | -PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n |
|
213 | +PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n |
|
214 | 214 | END; |
215 | 215 | } |
216 | 216 | $prefixes .= <<<END |
217 | -PREFIX wikibase: <{$rdfVocabulary->getNamespaceURI( RdfVocabulary::NS_ONTOLOGY )}>\n |
|
217 | +PREFIX wikibase: <{$rdfVocabulary->getNamespaceURI(RdfVocabulary::NS_ONTOLOGY)}>\n |
|
218 | 218 | END; |
219 | 219 | return $prefixes; |
220 | 220 | } |
@@ -226,22 +226,21 @@ discard block |
||
226 | 226 | * @return CachedBool |
227 | 227 | * @throws SparqlHelperException if the query times out or some other error occurs |
228 | 228 | */ |
229 | - public function hasType( $id, array $classes ) { |
|
230 | - $subclassOfId = $this->config->get( 'WBQualityConstraintsSubclassOfId' ); |
|
229 | + public function hasType($id, array $classes) { |
|
230 | + $subclassOfId = $this->config->get('WBQualityConstraintsSubclassOfId'); |
|
231 | 231 | // TODO hint:gearing is a workaround for T168973 and can hopefully be removed eventually |
232 | - $gearingHint = $this->config->get( 'WBQualityConstraintsSparqlHasWikibaseSupport' ) ? |
|
233 | - ' hint:Prior hint:gearing "forward".' : |
|
234 | - ''; |
|
232 | + $gearingHint = $this->config->get('WBQualityConstraintsSparqlHasWikibaseSupport') ? |
|
233 | + ' hint:Prior hint:gearing "forward".' : ''; |
|
235 | 234 | |
236 | 235 | $metadatas = []; |
237 | 236 | |
238 | - foreach ( array_chunk( $classes, 20 ) as $classesChunk ) { |
|
239 | - $classesValues = implode( ' ', array_map( |
|
240 | - function( $class ) { |
|
241 | - return 'wd:' . $class; |
|
237 | + foreach (array_chunk($classes, 20) as $classesChunk) { |
|
238 | + $classesValues = implode(' ', array_map( |
|
239 | + function($class) { |
|
240 | + return 'wd:'.$class; |
|
242 | 241 | }, |
243 | 242 | $classesChunk |
244 | - ) ); |
|
243 | + )); |
|
245 | 244 | |
246 | 245 | $query = <<<EOF |
247 | 246 | ASK { |
@@ -251,19 +250,19 @@ discard block |
||
251 | 250 | } |
252 | 251 | EOF; |
253 | 252 | |
254 | - $result = $this->runQuery( $query ); |
|
253 | + $result = $this->runQuery($query); |
|
255 | 254 | $metadatas[] = $result->getMetadata(); |
256 | - if ( $result->getArray()['boolean'] ) { |
|
255 | + if ($result->getArray()['boolean']) { |
|
257 | 256 | return new CachedBool( |
258 | 257 | true, |
259 | - Metadata::merge( $metadatas ) |
|
258 | + Metadata::merge($metadatas) |
|
260 | 259 | ); |
261 | 260 | } |
262 | 261 | } |
263 | 262 | |
264 | 263 | return new CachedBool( |
265 | 264 | false, |
266 | - Metadata::merge( $metadatas ) |
|
265 | + Metadata::merge($metadatas) |
|
267 | 266 | ); |
268 | 267 | } |
269 | 268 | |
@@ -279,10 +278,10 @@ discard block |
||
279 | 278 | $ignoreDeprecatedStatements |
280 | 279 | ) { |
281 | 280 | $pid = $statement->getPropertyId()->serialize(); |
282 | - $guid = str_replace( '$', '-', $statement->getGuid() ); |
|
281 | + $guid = str_replace('$', '-', $statement->getGuid()); |
|
283 | 282 | |
284 | 283 | $deprecatedFilter = ''; |
285 | - if ( $ignoreDeprecatedStatements ) { |
|
284 | + if ($ignoreDeprecatedStatements) { |
|
286 | 285 | $deprecatedFilter = 'MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. }'; |
287 | 286 | } |
288 | 287 | |
@@ -301,9 +300,9 @@ discard block |
||
301 | 300 | LIMIT 10 |
302 | 301 | EOF; |
303 | 302 | |
304 | - $result = $this->runQuery( $query ); |
|
303 | + $result = $this->runQuery($query); |
|
305 | 304 | |
306 | - return $this->getOtherEntities( $result ); |
|
305 | + return $this->getOtherEntities($result); |
|
307 | 306 | } |
308 | 307 | |
309 | 308 | /** |
@@ -328,16 +327,15 @@ discard block |
||
328 | 327 | $dataType = $this->propertyDataTypeLookup->getDataTypeIdForProperty( |
329 | 328 | $snak->getPropertyId() |
330 | 329 | ); |
331 | - list( $value, $isFullValue ) = $this->getRdfLiteral( $dataType, $dataValue ); |
|
332 | - if ( $isFullValue ) { |
|
330 | + list($value, $isFullValue) = $this->getRdfLiteral($dataType, $dataValue); |
|
331 | + if ($isFullValue) { |
|
333 | 332 | $prefix .= 'v'; |
334 | 333 | } |
335 | 334 | $path = $type === Context::TYPE_QUALIFIER ? |
336 | - "$prefix:$pid" : |
|
337 | - "prov:wasDerivedFrom/$prefix:$pid"; |
|
335 | + "$prefix:$pid" : "prov:wasDerivedFrom/$prefix:$pid"; |
|
338 | 336 | |
339 | 337 | $deprecatedFilter = ''; |
340 | - if ( $ignoreDeprecatedStatements ) { |
|
338 | + if ($ignoreDeprecatedStatements) { |
|
341 | 339 | $deprecatedFilter = <<< EOF |
342 | 340 | MINUS { ?otherStatement wikibase:rank wikibase:DeprecatedRank. } |
343 | 341 | EOF; |
@@ -357,9 +355,9 @@ discard block |
||
357 | 355 | LIMIT 10 |
358 | 356 | EOF; |
359 | 357 | |
360 | - $result = $this->runQuery( $query ); |
|
358 | + $result = $this->runQuery($query); |
|
361 | 359 | |
362 | - return $this->getOtherEntities( $result ); |
|
360 | + return $this->getOtherEntities($result); |
|
363 | 361 | } |
364 | 362 | |
365 | 363 | /** |
@@ -369,8 +367,8 @@ discard block |
||
369 | 367 | * |
370 | 368 | * @return string |
371 | 369 | */ |
372 | - private function stringLiteral( $text ) { |
|
373 | - return '"' . strtr( $text, [ '"' => '\\"', '\\' => '\\\\' ] ) . '"'; |
|
370 | + private function stringLiteral($text) { |
|
371 | + return '"'.strtr($text, ['"' => '\\"', '\\' => '\\\\']).'"'; |
|
374 | 372 | } |
375 | 373 | |
376 | 374 | /** |
@@ -380,18 +378,18 @@ discard block |
||
380 | 378 | * |
381 | 379 | * @return CachedEntityIds |
382 | 380 | */ |
383 | - private function getOtherEntities( CachedQueryResults $results ) { |
|
384 | - return new CachedEntityIds( array_map( |
|
385 | - function ( $resultBindings ) { |
|
381 | + private function getOtherEntities(CachedQueryResults $results) { |
|
382 | + return new CachedEntityIds(array_map( |
|
383 | + function($resultBindings) { |
|
386 | 384 | $entityIRI = $resultBindings['otherEntity']['value']; |
387 | - foreach ( $this->entityPrefixes as $entityPrefix ) { |
|
388 | - $entityPrefixLength = strlen( $entityPrefix ); |
|
389 | - if ( substr( $entityIRI, 0, $entityPrefixLength ) === $entityPrefix ) { |
|
385 | + foreach ($this->entityPrefixes as $entityPrefix) { |
|
386 | + $entityPrefixLength = strlen($entityPrefix); |
|
387 | + if (substr($entityIRI, 0, $entityPrefixLength) === $entityPrefix) { |
|
390 | 388 | try { |
391 | 389 | return $this->entityIdParser->parse( |
392 | - substr( $entityIRI, $entityPrefixLength ) |
|
390 | + substr($entityIRI, $entityPrefixLength) |
|
393 | 391 | ); |
394 | - } catch ( EntityIdParsingException $e ) { |
|
392 | + } catch (EntityIdParsingException $e) { |
|
395 | 393 | // fall through |
396 | 394 | } |
397 | 395 | } |
@@ -402,7 +400,7 @@ discard block |
||
402 | 400 | return null; |
403 | 401 | }, |
404 | 402 | $results->getArray()['results']['bindings'] |
405 | - ), $results->getMetadata() ); |
|
403 | + ), $results->getMetadata()); |
|
406 | 404 | } |
407 | 405 | |
408 | 406 | // @codingStandardsIgnoreStart cyclomatic complexity of this function is too high |
@@ -415,49 +413,49 @@ discard block |
||
415 | 413 | * @return array the literal or IRI as a string in SPARQL syntax, |
416 | 414 | * and a boolean indicating whether it refers to a full value node or not |
417 | 415 | */ |
418 | - private function getRdfLiteral( $dataType, DataValue $dataValue ) { |
|
419 | - switch ( $dataType ) { |
|
416 | + private function getRdfLiteral($dataType, DataValue $dataValue) { |
|
417 | + switch ($dataType) { |
|
420 | 418 | case 'string': |
421 | 419 | case 'external-id': |
422 | - return [ $this->stringLiteral( $dataValue->getValue() ), false ]; |
|
420 | + return [$this->stringLiteral($dataValue->getValue()), false]; |
|
423 | 421 | case 'commonsMedia': |
424 | - $url = $this->rdfVocabulary->getMediaFileURI( $dataValue->getValue() ); |
|
425 | - return [ '<' . $url . '>', false ]; |
|
422 | + $url = $this->rdfVocabulary->getMediaFileURI($dataValue->getValue()); |
|
423 | + return ['<'.$url.'>', false]; |
|
426 | 424 | case 'geo-shape': |
427 | - $url = $this->rdfVocabulary->getGeoShapeURI( $dataValue->getValue() ); |
|
428 | - return [ '<' . $url . '>', false ]; |
|
425 | + $url = $this->rdfVocabulary->getGeoShapeURI($dataValue->getValue()); |
|
426 | + return ['<'.$url.'>', false]; |
|
429 | 427 | case 'tabular-data': |
430 | - $url = $this->rdfVocabulary->getTabularDataURI( $dataValue->getValue() ); |
|
431 | - return [ '<' . $url . '>', false ]; |
|
428 | + $url = $this->rdfVocabulary->getTabularDataURI($dataValue->getValue()); |
|
429 | + return ['<'.$url.'>', false]; |
|
432 | 430 | case 'url': |
433 | 431 | $url = $dataValue->getValue(); |
434 | - if ( !preg_match( '/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url ) ) { |
|
432 | + if (!preg_match('/^[^<>"{}\\\\|^`\\x00-\\x20]*$/D', $url)) { |
|
435 | 433 | // not a valid URL for SPARQL (see SPARQL spec, production 139 IRIREF) |
436 | 434 | // such an URL should never reach us, so just throw |
437 | - throw new InvalidArgumentException( 'invalid URL: ' . $url ); |
|
435 | + throw new InvalidArgumentException('invalid URL: '.$url); |
|
438 | 436 | } |
439 | - return [ '<' . $url . '>', false ]; |
|
437 | + return ['<'.$url.'>', false]; |
|
440 | 438 | case 'wikibase-item': |
441 | 439 | case 'wikibase-property': |
442 | 440 | /** @var EntityIdValue $dataValue */ |
443 | 441 | '@phan-var EntityIdValue $dataValue'; |
444 | - return [ 'wd:' . $dataValue->getEntityId()->getSerialization(), false ]; |
|
442 | + return ['wd:'.$dataValue->getEntityId()->getSerialization(), false]; |
|
445 | 443 | case 'monolingualtext': |
446 | 444 | /** @var MonolingualTextValue $dataValue */ |
447 | 445 | '@phan-var MonolingualTextValue $dataValue'; |
448 | 446 | $lang = $dataValue->getLanguageCode(); |
449 | - if ( !preg_match( '/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang ) ) { |
|
447 | + if (!preg_match('/^[a-zA-Z]+(-[a-zA-Z0-9]+)*$/D', $lang)) { |
|
450 | 448 | // not a valid language tag for SPARQL (see SPARQL spec, production 145 LANGTAG) |
451 | 449 | // such a language tag should never reach us, so just throw |
452 | - throw new InvalidArgumentException( 'invalid language tag: ' . $lang ); |
|
450 | + throw new InvalidArgumentException('invalid language tag: '.$lang); |
|
453 | 451 | } |
454 | - return [ $this->stringLiteral( $dataValue->getText() ) . '@' . $lang, false ]; |
|
452 | + return [$this->stringLiteral($dataValue->getText()).'@'.$lang, false]; |
|
455 | 453 | case 'globe-coordinate': |
456 | 454 | case 'quantity': |
457 | 455 | case 'time': |
458 | - return [ 'wdv:' . $dataValue->getHash(), true ]; |
|
456 | + return ['wdv:'.$dataValue->getHash(), true]; |
|
459 | 457 | default: |
460 | - throw new InvalidArgumentException( 'unknown data type: ' . $dataType ); |
|
458 | + throw new InvalidArgumentException('unknown data type: '.$dataType); |
|
461 | 459 | } |
462 | 460 | } |
463 | 461 | // @codingStandardsIgnoreEnd |
@@ -470,44 +468,44 @@ discard block |
||
470 | 468 | * @throws SparqlHelperException if the query times out or some other error occurs |
471 | 469 | * @throws ConstraintParameterException if the $regex is invalid |
472 | 470 | */ |
473 | - public function matchesRegularExpression( $text, $regex ) { |
|
471 | + public function matchesRegularExpression($text, $regex) { |
|
474 | 472 | // caching wrapper around matchesRegularExpressionWithSparql |
475 | 473 | |
476 | - $textHash = hash( 'sha256', $text ); |
|
474 | + $textHash = hash('sha256', $text); |
|
477 | 475 | $cacheKey = $this->cache->makeKey( |
478 | 476 | 'WikibaseQualityConstraints', // extension |
479 | 477 | 'regex', // action |
480 | 478 | 'WDQS-Java', // regex flavor |
481 | - hash( 'sha256', $regex ) |
|
479 | + hash('sha256', $regex) |
|
482 | 480 | ); |
483 | - $cacheMapSize = $this->config->get( 'WBQualityConstraintsFormatCacheMapSize' ); |
|
481 | + $cacheMapSize = $this->config->get('WBQualityConstraintsFormatCacheMapSize'); |
|
484 | 482 | |
485 | 483 | $cacheMapArray = $this->cache->getWithSetCallback( |
486 | 484 | $cacheKey, |
487 | 485 | WANObjectCache::TTL_DAY, |
488 | - function( $cacheMapArray ) use ( $text, $regex, $textHash, $cacheMapSize ) { |
|
486 | + function($cacheMapArray) use ($text, $regex, $textHash, $cacheMapSize) { |
|
489 | 487 | // Initialize the cache map if not set |
490 | - if ( $cacheMapArray === false ) { |
|
488 | + if ($cacheMapArray === false) { |
|
491 | 489 | $key = 'wikibase.quality.constraints.regex.cache.refresh.init'; |
492 | - $this->dataFactory->increment( $key ); |
|
490 | + $this->dataFactory->increment($key); |
|
493 | 491 | return []; |
494 | 492 | } |
495 | 493 | |
496 | 494 | $key = 'wikibase.quality.constraints.regex.cache.refresh'; |
497 | - $this->dataFactory->increment( $key ); |
|
498 | - $cacheMap = MapCacheLRU::newFromArray( $cacheMapArray, $cacheMapSize ); |
|
499 | - if ( $cacheMap->has( $textHash ) ) { |
|
495 | + $this->dataFactory->increment($key); |
|
496 | + $cacheMap = MapCacheLRU::newFromArray($cacheMapArray, $cacheMapSize); |
|
497 | + if ($cacheMap->has($textHash)) { |
|
500 | 498 | $key = 'wikibase.quality.constraints.regex.cache.refresh.hit'; |
501 | - $this->dataFactory->increment( $key ); |
|
502 | - $cacheMap->get( $textHash ); // ping cache |
|
499 | + $this->dataFactory->increment($key); |
|
500 | + $cacheMap->get($textHash); // ping cache |
|
503 | 501 | } else { |
504 | 502 | $key = 'wikibase.quality.constraints.regex.cache.refresh.miss'; |
505 | - $this->dataFactory->increment( $key ); |
|
503 | + $this->dataFactory->increment($key); |
|
506 | 504 | try { |
507 | - $matches = $this->matchesRegularExpressionWithSparql( $text, $regex ); |
|
508 | - } catch ( ConstraintParameterException $e ) { |
|
509 | - $matches = $this->serializeConstraintParameterException( $e ); |
|
510 | - } catch ( SparqlHelperException $e ) { |
|
505 | + $matches = $this->matchesRegularExpressionWithSparql($text, $regex); |
|
506 | + } catch (ConstraintParameterException $e) { |
|
507 | + $matches = $this->serializeConstraintParameterException($e); |
|
508 | + } catch (SparqlHelperException $e) { |
|
511 | 509 | // don’t cache this |
512 | 510 | return $cacheMap->toArray(); |
513 | 511 | } |
@@ -531,42 +529,42 @@ discard block |
||
531 | 529 | ] |
532 | 530 | ); |
533 | 531 | |
534 | - if ( isset( $cacheMapArray[$textHash] ) ) { |
|
532 | + if (isset($cacheMapArray[$textHash])) { |
|
535 | 533 | $key = 'wikibase.quality.constraints.regex.cache.hit'; |
536 | - $this->dataFactory->increment( $key ); |
|
534 | + $this->dataFactory->increment($key); |
|
537 | 535 | $matches = $cacheMapArray[$textHash]; |
538 | - if ( is_bool( $matches ) ) { |
|
536 | + if (is_bool($matches)) { |
|
539 | 537 | return $matches; |
540 | - } elseif ( is_array( $matches ) && |
|
541 | - $matches['type'] == ConstraintParameterException::class ) { |
|
542 | - throw $this->deserializeConstraintParameterException( $matches ); |
|
538 | + } elseif (is_array($matches) && |
|
539 | + $matches['type'] == ConstraintParameterException::class) { |
|
540 | + throw $this->deserializeConstraintParameterException($matches); |
|
543 | 541 | } else { |
544 | 542 | throw new MWException( |
545 | - 'Value of unknown type in object cache (' . |
|
546 | - 'cache key: ' . $cacheKey . ', ' . |
|
547 | - 'cache map key: ' . $textHash . ', ' . |
|
548 | - 'value type: ' . gettype( $matches ) . ')' |
|
543 | + 'Value of unknown type in object cache ('. |
|
544 | + 'cache key: '.$cacheKey.', '. |
|
545 | + 'cache map key: '.$textHash.', '. |
|
546 | + 'value type: '.gettype($matches).')' |
|
549 | 547 | ); |
550 | 548 | } |
551 | 549 | } else { |
552 | 550 | $key = 'wikibase.quality.constraints.regex.cache.miss'; |
553 | - $this->dataFactory->increment( $key ); |
|
554 | - return $this->matchesRegularExpressionWithSparql( $text, $regex ); |
|
551 | + $this->dataFactory->increment($key); |
|
552 | + return $this->matchesRegularExpressionWithSparql($text, $regex); |
|
555 | 553 | } |
556 | 554 | } |
557 | 555 | |
558 | - private function serializeConstraintParameterException( ConstraintParameterException $cpe ) { |
|
556 | + private function serializeConstraintParameterException(ConstraintParameterException $cpe) { |
|
559 | 557 | return [ |
560 | 558 | 'type' => ConstraintParameterException::class, |
561 | - 'violationMessage' => $this->violationMessageSerializer->serialize( $cpe->getViolationMessage() ), |
|
559 | + 'violationMessage' => $this->violationMessageSerializer->serialize($cpe->getViolationMessage()), |
|
562 | 560 | ]; |
563 | 561 | } |
564 | 562 | |
565 | - private function deserializeConstraintParameterException( array $serialization ) { |
|
563 | + private function deserializeConstraintParameterException(array $serialization) { |
|
566 | 564 | $message = $this->violationMessageDeserializer->deserialize( |
567 | 565 | $serialization['violationMessage'] |
568 | 566 | ); |
569 | - return new ConstraintParameterException( $message ); |
|
567 | + return new ConstraintParameterException($message); |
|
570 | 568 | } |
571 | 569 | |
572 | 570 | /** |
@@ -580,25 +578,25 @@ discard block |
||
580 | 578 | * @throws SparqlHelperException if the query times out or some other error occurs |
581 | 579 | * @throws ConstraintParameterException if the $regex is invalid |
582 | 580 | */ |
583 | - public function matchesRegularExpressionWithSparql( $text, $regex ) { |
|
584 | - $textStringLiteral = $this->stringLiteral( $text ); |
|
585 | - $regexStringLiteral = $this->stringLiteral( '^(?:' . $regex . ')$' ); |
|
581 | + public function matchesRegularExpressionWithSparql($text, $regex) { |
|
582 | + $textStringLiteral = $this->stringLiteral($text); |
|
583 | + $regexStringLiteral = $this->stringLiteral('^(?:'.$regex.')$'); |
|
586 | 584 | |
587 | 585 | $query = <<<EOF |
588 | 586 | SELECT (REGEX($textStringLiteral, $regexStringLiteral) AS ?matches) {} |
589 | 587 | EOF; |
590 | 588 | |
591 | - $result = $this->runQuery( $query, false ); |
|
589 | + $result = $this->runQuery($query, false); |
|
592 | 590 | |
593 | 591 | $vars = $result->getArray()['results']['bindings'][0]; |
594 | - if ( array_key_exists( 'matches', $vars ) ) { |
|
592 | + if (array_key_exists('matches', $vars)) { |
|
595 | 593 | // true or false ⇒ regex okay, text matches or not |
596 | 594 | return $vars['matches']['value'] === 'true'; |
597 | 595 | } else { |
598 | 596 | // empty result: regex broken |
599 | 597 | throw new ConstraintParameterException( |
600 | - ( new ViolationMessage( 'wbqc-violation-message-parameter-regex' ) ) |
|
601 | - ->withInlineCode( $regex, Role::CONSTRAINT_PARAMETER_VALUE ) |
|
598 | + (new ViolationMessage('wbqc-violation-message-parameter-regex')) |
|
599 | + ->withInlineCode($regex, Role::CONSTRAINT_PARAMETER_VALUE) |
|
602 | 600 | ); |
603 | 601 | } |
604 | 602 | } |
@@ -610,14 +608,14 @@ discard block |
||
610 | 608 | * |
611 | 609 | * @return boolean |
612 | 610 | */ |
613 | - public function isTimeout( $responseContent ) { |
|
614 | - $timeoutRegex = implode( '|', array_map( |
|
615 | - function ( $fqn ) { |
|
616 | - return preg_quote( $fqn, '/' ); |
|
611 | + public function isTimeout($responseContent) { |
|
612 | + $timeoutRegex = implode('|', array_map( |
|
613 | + function($fqn) { |
|
614 | + return preg_quote($fqn, '/'); |
|
617 | 615 | }, |
618 | - $this->config->get( 'WBQualityConstraintsSparqlTimeoutExceptionClasses' ) |
|
619 | - ) ); |
|
620 | - return (bool)preg_match( '/' . $timeoutRegex . '/', $responseContent ); |
|
616 | + $this->config->get('WBQualityConstraintsSparqlTimeoutExceptionClasses') |
|
617 | + )); |
|
618 | + return (bool) preg_match('/'.$timeoutRegex.'/', $responseContent); |
|
621 | 619 | } |
622 | 620 | |
623 | 621 | /** |
@@ -629,17 +627,17 @@ discard block |
||
629 | 627 | * @return int|boolean the max-age (in seconds) |
630 | 628 | * or a plain boolean if no max-age can be determined |
631 | 629 | */ |
632 | - public function getCacheMaxAge( $responseHeaders ) { |
|
630 | + public function getCacheMaxAge($responseHeaders) { |
|
633 | 631 | if ( |
634 | - array_key_exists( 'x-cache-status', $responseHeaders ) && |
|
635 | - preg_match( '/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0] ) |
|
632 | + array_key_exists('x-cache-status', $responseHeaders) && |
|
633 | + preg_match('/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0]) |
|
636 | 634 | ) { |
637 | 635 | $maxage = []; |
638 | 636 | if ( |
639 | - array_key_exists( 'cache-control', $responseHeaders ) && |
|
640 | - preg_match( '/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage ) |
|
637 | + array_key_exists('cache-control', $responseHeaders) && |
|
638 | + preg_match('/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage) |
|
641 | 639 | ) { |
642 | - return intval( $maxage[1] ); |
|
640 | + return intval($maxage[1]); |
|
643 | 641 | } else { |
644 | 642 | return true; |
645 | 643 | } |
@@ -660,34 +658,34 @@ discard block |
||
660 | 658 | * or SparlHelper::EMPTY_RETRY_AFTER if there is an empty Retry-After |
661 | 659 | * or SparlHelper::INVALID_RETRY_AFTER if there is something wrong with the format |
662 | 660 | */ |
663 | - public function getThrottling( MWHttpRequest $request ) { |
|
664 | - $retryAfterValue = $request->getResponseHeader( 'Retry-After' ); |
|
665 | - if ( $retryAfterValue === null ) { |
|
661 | + public function getThrottling(MWHttpRequest $request) { |
|
662 | + $retryAfterValue = $request->getResponseHeader('Retry-After'); |
|
663 | + if ($retryAfterValue === null) { |
|
666 | 664 | return self::NO_RETRY_AFTER; |
667 | 665 | } |
668 | 666 | |
669 | - $trimmedRetryAfterValue = trim( $retryAfterValue ); |
|
670 | - if ( empty( $trimmedRetryAfterValue ) ) { |
|
667 | + $trimmedRetryAfterValue = trim($retryAfterValue); |
|
668 | + if (empty($trimmedRetryAfterValue)) { |
|
671 | 669 | return self::EMPTY_RETRY_AFTER; |
672 | 670 | } |
673 | 671 | |
674 | - if ( is_numeric( $trimmedRetryAfterValue ) ) { |
|
675 | - $delaySeconds = (int)$trimmedRetryAfterValue; |
|
676 | - if ( $delaySeconds >= 0 ) { |
|
677 | - return $this->getTimestampInFuture( new DateInterval( 'PT' . $delaySeconds . 'S' ) ); |
|
672 | + if (is_numeric($trimmedRetryAfterValue)) { |
|
673 | + $delaySeconds = (int) $trimmedRetryAfterValue; |
|
674 | + if ($delaySeconds >= 0) { |
|
675 | + return $this->getTimestampInFuture(new DateInterval('PT'.$delaySeconds.'S')); |
|
678 | 676 | } |
679 | 677 | } else { |
680 | - $return = strtotime( $trimmedRetryAfterValue ); |
|
681 | - if ( !empty( $return ) ) { |
|
682 | - return new ConvertibleTimestamp( $return ); |
|
678 | + $return = strtotime($trimmedRetryAfterValue); |
|
679 | + if (!empty($return)) { |
|
680 | + return new ConvertibleTimestamp($return); |
|
683 | 681 | } |
684 | 682 | } |
685 | 683 | return self::INVALID_RETRY_AFTER; |
686 | 684 | } |
687 | 685 | |
688 | - private function getTimestampInFuture( DateInterval $delta ) { |
|
686 | + private function getTimestampInFuture(DateInterval $delta) { |
|
689 | 687 | $now = new ConvertibleTimestamp(); |
690 | - return new ConvertibleTimestamp( $now->timestamp->add( $delta ) ); |
|
688 | + return new ConvertibleTimestamp($now->timestamp->add($delta)); |
|
691 | 689 | } |
692 | 690 | |
693 | 691 | /** |
@@ -701,68 +699,67 @@ discard block |
||
701 | 699 | * |
702 | 700 | * @throws SparqlHelperException if the query times out or some other error occurs |
703 | 701 | */ |
704 | - public function runQuery( $query, $needsPrefixes = true ) { |
|
702 | + public function runQuery($query, $needsPrefixes = true) { |
|
705 | 703 | |
706 | - if ( $this->throttlingLock->isLocked( self::EXPIRY_LOCK_ID ) ) { |
|
707 | - $this->dataFactory->increment( 'wikibase.quality.constraints.sparql.throttling' ); |
|
704 | + if ($this->throttlingLock->isLocked(self::EXPIRY_LOCK_ID)) { |
|
705 | + $this->dataFactory->increment('wikibase.quality.constraints.sparql.throttling'); |
|
708 | 706 | throw new TooManySparqlRequestsException(); |
709 | 707 | } |
710 | 708 | |
711 | - $endpoint = $this->config->get( 'WBQualityConstraintsSparqlEndpoint' ); |
|
712 | - $maxQueryTimeMillis = $this->config->get( 'WBQualityConstraintsSparqlMaxMillis' ); |
|
709 | + $endpoint = $this->config->get('WBQualityConstraintsSparqlEndpoint'); |
|
710 | + $maxQueryTimeMillis = $this->config->get('WBQualityConstraintsSparqlMaxMillis'); |
|
713 | 711 | |
714 | - if ( $this->config->get( 'WBQualityConstraintsSparqlHasWikibaseSupport' ) ) { |
|
712 | + if ($this->config->get('WBQualityConstraintsSparqlHasWikibaseSupport')) { |
|
715 | 713 | $needsPrefixes = false; |
716 | 714 | } |
717 | 715 | |
718 | - if ( $needsPrefixes ) { |
|
719 | - $query = $this->prefixes . $query; |
|
716 | + if ($needsPrefixes) { |
|
717 | + $query = $this->prefixes.$query; |
|
720 | 718 | } |
721 | - $query = "#wbqc\n" . $query; |
|
719 | + $query = "#wbqc\n".$query; |
|
722 | 720 | |
723 | - $url = $endpoint . '?' . http_build_query( |
|
721 | + $url = $endpoint.'?'.http_build_query( |
|
724 | 722 | [ |
725 | 723 | 'query' => $query, |
726 | 724 | 'format' => 'json', |
727 | 725 | 'maxQueryTimeMillis' => $maxQueryTimeMillis, |
728 | 726 | ], |
729 | - null, ini_get( 'arg_separator.output' ), |
|
727 | + null, ini_get('arg_separator.output'), |
|
730 | 728 | // encode spaces with %20, not + |
731 | 729 | PHP_QUERY_RFC3986 |
732 | 730 | ); |
733 | 731 | |
734 | 732 | $options = [ |
735 | 733 | 'method' => 'GET', |
736 | - 'timeout' => (int)round( ( $maxQueryTimeMillis + 1000 ) / 1000 ), |
|
734 | + 'timeout' => (int) round(($maxQueryTimeMillis + 1000) / 1000), |
|
737 | 735 | 'connectTimeout' => 'default', |
738 | 736 | 'userAgent' => $this->defaultUserAgent, |
739 | 737 | ]; |
740 | - $request = $this->requestFactory->create( $url, $options, __METHOD__ ); |
|
741 | - $startTime = microtime( true ); |
|
738 | + $request = $this->requestFactory->create($url, $options, __METHOD__); |
|
739 | + $startTime = microtime(true); |
|
742 | 740 | $requestStatus = $request->execute(); |
743 | - $endTime = microtime( true ); |
|
741 | + $endTime = microtime(true); |
|
744 | 742 | $this->dataFactory->timing( |
745 | 743 | 'wikibase.quality.constraints.sparql.timing', |
746 | - ( $endTime - $startTime ) * 1000 |
|
744 | + ($endTime - $startTime) * 1000 |
|
747 | 745 | ); |
748 | 746 | |
749 | - $this->guardAgainstTooManyRequestsError( $request ); |
|
747 | + $this->guardAgainstTooManyRequestsError($request); |
|
750 | 748 | |
751 | - $maxAge = $this->getCacheMaxAge( $request->getResponseHeaders() ); |
|
752 | - if ( $maxAge ) { |
|
753 | - $this->dataFactory->increment( 'wikibase.quality.constraints.sparql.cached' ); |
|
749 | + $maxAge = $this->getCacheMaxAge($request->getResponseHeaders()); |
|
750 | + if ($maxAge) { |
|
751 | + $this->dataFactory->increment('wikibase.quality.constraints.sparql.cached'); |
|
754 | 752 | } |
755 | 753 | |
756 | - if ( $requestStatus->isOK() ) { |
|
754 | + if ($requestStatus->isOK()) { |
|
757 | 755 | $json = $request->getContent(); |
758 | - $jsonStatus = FormatJson::parse( $json, FormatJson::FORCE_ASSOC ); |
|
759 | - if ( $jsonStatus->isOK() ) { |
|
756 | + $jsonStatus = FormatJson::parse($json, FormatJson::FORCE_ASSOC); |
|
757 | + if ($jsonStatus->isOK()) { |
|
760 | 758 | return new CachedQueryResults( |
761 | 759 | $jsonStatus->getValue(), |
762 | 760 | Metadata::ofCachingMetadata( |
763 | 761 | $maxAge ? |
764 | - CachingMetadata::ofMaximumAgeInSeconds( $maxAge ) : |
|
765 | - CachingMetadata::fresh() |
|
762 | + CachingMetadata::ofMaximumAgeInSeconds($maxAge) : CachingMetadata::fresh() |
|
766 | 763 | ) |
767 | 764 | ); |
768 | 765 | } else { |
@@ -779,9 +776,9 @@ discard block |
||
779 | 776 | // fall through to general error handling |
780 | 777 | } |
781 | 778 | |
782 | - $this->dataFactory->increment( 'wikibase.quality.constraints.sparql.error' ); |
|
779 | + $this->dataFactory->increment('wikibase.quality.constraints.sparql.error'); |
|
783 | 780 | |
784 | - if ( $this->isTimeout( $request->getContent() ) ) { |
|
781 | + if ($this->isTimeout($request->getContent())) { |
|
785 | 782 | $this->dataFactory->increment( |
786 | 783 | 'wikibase.quality.constraints.sparql.error.timeout' |
787 | 784 | ); |
@@ -796,29 +793,29 @@ discard block |
||
796 | 793 | * @param MWHttpRequest $request |
797 | 794 | * @throws TooManySparqlRequestsException |
798 | 795 | */ |
799 | - private function guardAgainstTooManyRequestsError( MWHttpRequest $request ): void { |
|
800 | - if ( $request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS ) { |
|
796 | + private function guardAgainstTooManyRequestsError(MWHttpRequest $request): void { |
|
797 | + if ($request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS) { |
|
801 | 798 | return; |
802 | 799 | } |
803 | 800 | |
804 | - $fallbackBlockDuration = (int)$this->config->get( 'WBQualityConstraintsSparqlThrottlingFallbackDuration' ); |
|
801 | + $fallbackBlockDuration = (int) $this->config->get('WBQualityConstraintsSparqlThrottlingFallbackDuration'); |
|
805 | 802 | |
806 | - if ( $fallbackBlockDuration < 0 ) { |
|
807 | - throw new InvalidArgumentException( 'Fallback duration must be positive int but is: ' . |
|
808 | - $fallbackBlockDuration ); |
|
803 | + if ($fallbackBlockDuration < 0) { |
|
804 | + throw new InvalidArgumentException('Fallback duration must be positive int but is: '. |
|
805 | + $fallbackBlockDuration); |
|
809 | 806 | } |
810 | 807 | |
811 | - $this->dataFactory->increment( 'wikibase.quality.constraints.sparql.throttling' ); |
|
812 | - $throttlingUntil = $this->getThrottling( $request ); |
|
813 | - if ( !( $throttlingUntil instanceof ConvertibleTimestamp ) ) { |
|
814 | - $this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid( $request ); |
|
808 | + $this->dataFactory->increment('wikibase.quality.constraints.sparql.throttling'); |
|
809 | + $throttlingUntil = $this->getThrottling($request); |
|
810 | + if (!($throttlingUntil instanceof ConvertibleTimestamp)) { |
|
811 | + $this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid($request); |
|
815 | 812 | $this->throttlingLock->lock( |
816 | 813 | self::EXPIRY_LOCK_ID, |
817 | - $this->getTimestampInFuture( new DateInterval( 'PT' . $fallbackBlockDuration . 'S' ) ) |
|
814 | + $this->getTimestampInFuture(new DateInterval('PT'.$fallbackBlockDuration.'S')) |
|
818 | 815 | ); |
819 | 816 | } else { |
820 | - $this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent( $throttlingUntil, $request ); |
|
821 | - $this->throttlingLock->lock( self::EXPIRY_LOCK_ID, $throttlingUntil ); |
|
817 | + $this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent($throttlingUntil, $request); |
|
818 | + $this->throttlingLock->lock(self::EXPIRY_LOCK_ID, $throttlingUntil); |
|
822 | 819 | } |
823 | 820 | throw new TooManySparqlRequestsException(); |
824 | 821 | } |