Completed
Push — master ( e0d9db...fc532a )
by
unknown
20s
created
src/Api/ExpiryLock.php 1 patch
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare( strict_types = 1 );
3
+declare(strict_types=1);
4 4
 
5 5
 namespace WikibaseQuality\ConstraintReport\Api;
6 6
 
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
 
22 22
 	private BagOStuff $cache;
23 23
 
24
-	public function __construct( BagOStuff $cache ) {
24
+	public function __construct(BagOStuff $cache) {
25 25
 		$this->cache = $cache;
26 26
 	}
27 27
 
@@ -32,9 +32,9 @@  discard block
 block discarded – undo
32 32
 	 *
33 33
 	 * @throws \Wikimedia\Assert\ParameterTypeException
34 34
 	 */
35
-	private function makeKey( string $id ): string {
36
-		if ( trim( $id ) === '' ) {
37
-			throw new ParameterTypeException( '$id', 'non-empty string' );
35
+	private function makeKey(string $id): string {
36
+		if (trim($id) === '') {
37
+			throw new ParameterTypeException('$id', 'non-empty string');
38 38
 		}
39 39
 
40 40
 		return $this->cache->makeKey(
@@ -52,15 +52,15 @@  discard block
 block discarded – undo
52 52
 	 *
53 53
 	 * @throws \Wikimedia\Assert\ParameterTypeException
54 54
 	 */
55
-	public function lock( string $id, ConvertibleTimestamp $expiryTimestamp ): bool {
55
+	public function lock(string $id, ConvertibleTimestamp $expiryTimestamp): bool {
56 56
 
57
-		$cacheId = $this->makeKey( $id );
57
+		$cacheId = $this->makeKey($id);
58 58
 
59
-		if ( !$this->isLockedInternal( $cacheId ) ) {
59
+		if (!$this->isLockedInternal($cacheId)) {
60 60
 			return $this->cache->set(
61 61
 				$cacheId,
62
-				$expiryTimestamp->getTimestamp( TS_UNIX ),
63
-				(int)$expiryTimestamp->getTimestamp( TS_UNIX )
62
+				$expiryTimestamp->getTimestamp(TS_UNIX),
63
+				(int) $expiryTimestamp->getTimestamp(TS_UNIX)
64 64
 			);
65 65
 		} else {
66 66
 			return false;
@@ -74,20 +74,20 @@  discard block
 block discarded – undo
74 74
 	 *
75 75
 	 * @throws \Wikimedia\Assert\ParameterTypeException
76 76
 	 */
77
-	private function isLockedInternal( string $cacheId ): bool {
78
-		$expiryTime = $this->cache->get( $cacheId );
79
-		if ( !$expiryTime ) {
77
+	private function isLockedInternal(string $cacheId): bool {
78
+		$expiryTime = $this->cache->get($cacheId);
79
+		if (!$expiryTime) {
80 80
 			return false;
81 81
 		}
82 82
 
83 83
 		try {
84
-			$lockExpiryTimeStamp = new ConvertibleTimestamp( $expiryTime );
85
-		} catch ( TimestampException ) {
84
+			$lockExpiryTimeStamp = new ConvertibleTimestamp($expiryTime);
85
+		} catch (TimestampException) {
86 86
 			return false;
87 87
 		}
88 88
 
89 89
 		$now = new ConvertibleTimestamp();
90
-		if ( $now->timestamp < $lockExpiryTimeStamp->timestamp ) {
90
+		if ($now->timestamp < $lockExpiryTimeStamp->timestamp) {
91 91
 			return true;
92 92
 		} else {
93 93
 			return false;
@@ -101,8 +101,8 @@  discard block
 block discarded – undo
101 101
 	 *
102 102
 	 * @throws \Wikimedia\Assert\ParameterTypeException
103 103
 	 */
104
-	public function isLocked( string $id ): bool {
105
-		return $this->isLockedInternal( $this->makeKey( $id ) );
104
+	public function isLocked(string $id): bool {
105
+		return $this->isLockedInternal($this->makeKey($id));
106 106
 	}
107 107
 
108 108
 }
Please login to merge, or discard this patch.
src/ConstraintCheck/Result/NullResult.php 1 patch
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare( strict_types = 1 );
3
+declare(strict_types=1);
4 4
 
5 5
 // @phan-file-suppress PhanPluginNeverReturnMethod
6 6
 
@@ -28,22 +28,22 @@  discard block
 block discarded – undo
28 28
 	 */
29 29
 	private const NULL_PROPERTY_ID = 'P2147483647';
30 30
 
31
-	public function __construct( ContextCursor $contextCursor ) {
31
+	public function __construct(ContextCursor $contextCursor) {
32 32
 		$constraint = new Constraint(
33 33
 			'null',
34
-			new NumericPropertyId( self::NULL_PROPERTY_ID ),
34
+			new NumericPropertyId(self::NULL_PROPERTY_ID),
35 35
 			'none',
36 36
 			[]
37 37
 		);
38
-		parent::__construct( $contextCursor, $constraint );
38
+		parent::__construct($contextCursor, $constraint);
39 39
 	}
40 40
 
41 41
 	public function getConstraint(): Constraint {
42
-		throw new DomainException( 'NullResult holds no constraint' );
42
+		throw new DomainException('NullResult holds no constraint');
43 43
 	}
44 44
 
45 45
 	public function getConstraintId(): string {
46
-		throw new DomainException( 'NullResult holds no constraint' );
46
+		throw new DomainException('NullResult holds no constraint');
47 47
 	}
48 48
 
49 49
 }
Please login to merge, or discard this patch.
src/ConstraintCheck/Helper/DummySparqlHelper.php 1 patch
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare( strict_types = 1 );
3
+declare(strict_types=1);
4 4
 
5 5
 // @phan-file-suppress PhanPluginNeverReturnMethod
6 6
 
@@ -29,8 +29,8 @@  discard block
 block discarded – undo
29 29
 		// no parent::__construct() call
30 30
 	}
31 31
 
32
-	public function hasType( EntityId $id, array $classes ): CachedBool {
33
-		throw new LogicException( 'methods of this class should never be called' );
32
+	public function hasType(EntityId $id, array $classes): CachedBool {
33
+		throw new LogicException('methods of this class should never be called');
34 34
 	}
35 35
 
36 36
 	public function findEntitiesWithSameStatement(
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
 		Statement $statement,
39 39
 		array $separators
40 40
 	): CachedEntityIds {
41
-		throw new LogicException( 'methods of this class should never be called' );
41
+		throw new LogicException('methods of this class should never be called');
42 42
 	}
43 43
 
44 44
 	public function findEntitiesWithSameQualifierOrReference(
@@ -47,15 +47,15 @@  discard block
 block discarded – undo
47 47
 		string $type,
48 48
 		bool $ignoreDeprecatedStatements
49 49
 	): CachedEntityIds {
50
-		throw new LogicException( 'methods of this class should never be called' );
50
+		throw new LogicException('methods of this class should never be called');
51 51
 	}
52 52
 
53
-	public function matchesRegularExpression( string $text, string $regex ): bool {
54
-		throw new LogicException( 'methods of this class should never be called' );
53
+	public function matchesRegularExpression(string $text, string $regex): bool {
54
+		throw new LogicException('methods of this class should never be called');
55 55
 	}
56 56
 
57
-	public function runQuery( string $query, string $endpoint, bool $needsPrefixes = true ): CachedQueryResults {
58
-		throw new LogicException( 'methods of this class should never be called' );
57
+	public function runQuery(string $query, string $endpoint, bool $needsPrefixes = true): CachedQueryResults {
58
+		throw new LogicException('methods of this class should never be called');
59 59
 	}
60 60
 
61 61
 }
Please login to merge, or discard this patch.
src/ConstraintCheck/Context/EntityContextCursor.php 1 patch
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare( strict_types = 1 );
3
+declare(strict_types=1);
4 4
 
5 5
 // @phan-file-suppress PhanPluginNeverReturnMethod
6 6
 
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
 	 * @codeCoverageIgnore This method is not supported.
34 34
 	 */
35 35
 	public function getType(): string {
36
-		throw new LogicException( 'EntityContextCursor has no full associated context' );
36
+		throw new LogicException('EntityContextCursor has no full associated context');
37 37
 	}
38 38
 
39 39
 	public function getEntityId(): string {
@@ -44,35 +44,35 @@  discard block
 block discarded – undo
44 44
 	 * @codeCoverageIgnore This method is not supported.
45 45
 	 */
46 46
 	public function getStatementPropertyId(): string {
47
-		throw new LogicException( 'EntityContextCursor has no full associated context' );
47
+		throw new LogicException('EntityContextCursor has no full associated context');
48 48
 	}
49 49
 
50 50
 	/**
51 51
 	 * @codeCoverageIgnore This method is not supported.
52 52
 	 */
53 53
 	public function getStatementGuid(): string {
54
-		throw new LogicException( 'EntityContextCursor has no full associated context' );
54
+		throw new LogicException('EntityContextCursor has no full associated context');
55 55
 	}
56 56
 
57 57
 	/**
58 58
 	 * @codeCoverageIgnore This method is not supported.
59 59
 	 */
60 60
 	public function getSnakPropertyId(): string {
61
-		throw new LogicException( 'EntityContextCursor has no full associated context' );
61
+		throw new LogicException('EntityContextCursor has no full associated context');
62 62
 	}
63 63
 
64 64
 	/**
65 65
 	 * @codeCoverageIgnore This method is not supported.
66 66
 	 */
67 67
 	public function getSnakHash(): string {
68
-		throw new LogicException( 'EntityContextCursor has no full associated context' );
68
+		throw new LogicException('EntityContextCursor has no full associated context');
69 69
 	}
70 70
 
71 71
 	/**
72 72
 	 * @codeCoverageIgnore This method is not supported.
73 73
 	 */
74
-	public function &getMainArray( array &$container ): array {
75
-		throw new LogicException( 'EntityContextCursor cannot store check results' );
74
+	public function &getMainArray(array &$container): array {
75
+		throw new LogicException('EntityContextCursor cannot store check results');
76 76
 	}
77 77
 
78 78
 	/**
@@ -81,14 +81,14 @@  discard block
 block discarded – undo
81 81
 	 * @param ?array $result must be null
82 82
 	 * @param array[] &$container
83 83
 	 */
84
-	public function storeCheckResultInArray( ?array $result, array &$container ): void {
85
-		if ( $result !== null ) {
86
-			throw new LogicException( 'EntityContextCursor cannot store check results' );
84
+	public function storeCheckResultInArray(?array $result, array &$container): void {
85
+		if ($result !== null) {
86
+			throw new LogicException('EntityContextCursor cannot store check results');
87 87
 		}
88 88
 
89 89
 		// this ensures that the claims array is present in the $container,
90 90
 		// populating it if necessary, even though we ignore the return value
91
-		$this->getClaimsArray( $container );
91
+		$this->getClaimsArray($container);
92 92
 	}
93 93
 
94 94
 }
Please login to merge, or discard this patch.
src/ConstraintCheck/Message/ViolationMessageRenderer.php 1 patch
Spacing   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare( strict_types = 1 );
3
+declare(strict_types=1);
4 4
 
5 5
 namespace WikibaseQuality\ConstraintReport\ConstraintCheck\Message;
6 6
 
@@ -70,15 +70,15 @@  discard block
 block discarded – undo
70 70
 		$this->maxListLength = $maxListLength;
71 71
 	}
72 72
 
73
-	public function render( ViolationMessage $violationMessage ): string {
73
+	public function render(ViolationMessage $violationMessage): string {
74 74
 		$messageKey = $violationMessage->getMessageKey();
75
-		$paramsLists = [ [] ];
76
-		foreach ( $violationMessage->getArguments() as $argument ) {
77
-			$params = $this->renderArgument( $argument );
75
+		$paramsLists = [[]];
76
+		foreach ($violationMessage->getArguments() as $argument) {
77
+			$params = $this->renderArgument($argument);
78 78
 			$paramsLists[] = $params;
79 79
 		}
80
-		$allParams = array_merge( ...$paramsLists );
81
-		return $this->messageLocalizer->msg( $messageKey, ...$allParams )->escaped();
80
+		$allParams = array_merge(...$paramsLists);
81
+		return $this->messageLocalizer->msg($messageKey, ...$allParams)->escaped();
82 82
 	}
83 83
 
84 84
 	/**
@@ -86,13 +86,13 @@  discard block
 block discarded – undo
86 86
 	 * @param string|null $role one of the Role::* constants
87 87
 	 * @return string HTML
88 88
 	 */
89
-	protected function addRole( string $value, ?string $role ): string {
90
-		if ( $role === null ) {
89
+	protected function addRole(string $value, ?string $role): string {
90
+		if ($role === null) {
91 91
 			return $value;
92 92
 		}
93 93
 
94
-		return '<span class="wbqc-role wbqc-role-' . htmlspecialchars( $role ) . '">' .
95
-			$value .
94
+		return '<span class="wbqc-role wbqc-role-'.htmlspecialchars($role).'">'.
95
+			$value.
96 96
 			'</span>';
97 97
 	}
98 98
 
@@ -100,15 +100,15 @@  discard block
 block discarded – undo
100 100
 	 * @param string $key message key
101 101
 	 * @return string HTML
102 102
 	 */
103
-	protected function msgEscaped( string $key ): string {
104
-		return $this->messageLocalizer->msg( $key )->escaped();
103
+	protected function msgEscaped(string $key): string {
104
+		return $this->messageLocalizer->msg($key)->escaped();
105 105
 	}
106 106
 
107 107
 	/**
108 108
 	 * @param array $argument
109 109
 	 * @return MessageParam[] params (for Message::params)
110 110
 	 */
111
-	protected function renderArgument( array $argument ): array {
111
+	protected function renderArgument(array $argument): array {
112 112
 		$methods = [
113 113
 			ViolationMessage::TYPE_ENTITY_ID => 'renderEntityId',
114 114
 			ViolationMessage::TYPE_ENTITY_ID_LIST => 'renderEntityIdList',
@@ -129,12 +129,12 @@  discard block
 block discarded – undo
129 129
 		$value = $argument['value'];
130 130
 		$role = $argument['role'];
131 131
 
132
-		if ( array_key_exists( $type, $methods ) ) {
132
+		if (array_key_exists($type, $methods)) {
133 133
 			$method = $methods[$type];
134
-			$params = $this->$method( $value, $role );
134
+			$params = $this->$method($value, $role);
135 135
 		} else {
136 136
 			throw new InvalidArgumentException(
137
-				'Unknown ViolationMessage argument type ' . $type . '!'
137
+				'Unknown ViolationMessage argument type '.$type.'!'
138 138
 			);
139 139
 		}
140 140
 
@@ -148,34 +148,34 @@  discard block
 block discarded – undo
148 148
 	 * and return a single-element array with a raw message param (i. e. [ Message::rawParam( … ) ])
149 149
 	 * @return MessageParam[] list of parameters as accepted by Message::params()
150 150
 	 */
151
-	private function renderList( array $list, ?string $role, callable $render ): array {
152
-		if ( $list === [] ) {
151
+	private function renderList(array $list, ?string $role, callable $render): array {
152
+		if ($list === []) {
153 153
 			return [
154
-				Message::numParam( 0 ),
155
-				Message::rawParam( '<ul></ul>' ),
154
+				Message::numParam(0),
155
+				Message::rawParam('<ul></ul>'),
156 156
 			];
157 157
 		}
158 158
 
159
-		$truncated = count( $list ) > $this->maxListLength;
160
-		if ( $truncated ) {
161
-			$list = array_slice( $list, 0, $this->maxListLength );
159
+		$truncated = count($list) > $this->maxListLength;
160
+		if ($truncated) {
161
+			$list = array_slice($list, 0, $this->maxListLength);
162 162
 		}
163 163
 
164 164
 		$renderedParamsLists = array_map(
165 165
 			$render,
166 166
 			$list,
167
-			array_fill( 0, count( $list ), $role )
167
+			array_fill(0, count($list), $role)
168 168
 		);
169
-		$renderedParams = array_column( $renderedParamsLists, 0 );
170
-		$renderedElements = array_map( static fn ( MessageParam $p ) => $p->getValue(), $renderedParams );
171
-		if ( $truncated ) {
172
-			$renderedElements[] = $this->msgEscaped( 'ellipsis' );
169
+		$renderedParams = array_column($renderedParamsLists, 0);
170
+		$renderedElements = array_map(static fn (MessageParam $p) => $p->getValue(), $renderedParams);
171
+		if ($truncated) {
172
+			$renderedElements[] = $this->msgEscaped('ellipsis');
173 173
 		}
174 174
 
175 175
 		return [
176
-			Message::numParam( count( $list ) ),
176
+			Message::numParam(count($list)),
177 177
 			Message::rawParam(
178
-				'<ul><li>' . implode( '</li><li>', $renderedElements ) . '</li></ul>'
178
+				'<ul><li>'.implode('</li><li>', $renderedElements).'</li></ul>'
179 179
 			),
180 180
 			...$renderedParams,
181 181
 		];
@@ -186,11 +186,11 @@  discard block
 block discarded – undo
186 186
 	 * @param string|null $role one of the Role::* constants
187 187
 	 * @return MessageParam[] list of a single raw message param (i. e. [ Message::rawParam( … ) ])
188 188
 	 */
189
-	private function renderEntityId( EntityId $entityId, ?string $role ): array {
190
-		return [ Message::rawParam( $this->addRole(
191
-			$this->entityIdFormatter->formatEntityId( $entityId ),
189
+	private function renderEntityId(EntityId $entityId, ?string $role): array {
190
+		return [Message::rawParam($this->addRole(
191
+			$this->entityIdFormatter->formatEntityId($entityId),
192 192
 			$role
193
-		) ) ];
193
+		))];
194 194
 	}
195 195
 
196 196
 	/**
@@ -198,8 +198,8 @@  discard block
 block discarded – undo
198 198
 	 * @param string|null $role one of the Role::* constants
199 199
 	 * @return MessageParam[] list of parameters as accepted by Message::params()
200 200
 	 */
201
-	private function renderEntityIdList( array $entityIdList, ?string $role ): array {
202
-		return $this->renderList( $entityIdList, $role, [ $this, 'renderEntityId' ] );
201
+	private function renderEntityIdList(array $entityIdList, ?string $role): array {
202
+		return $this->renderList($entityIdList, $role, [$this, 'renderEntityId']);
203 203
 	}
204 204
 
205 205
 	/**
@@ -207,24 +207,24 @@  discard block
 block discarded – undo
207 207
 	 * @param string|null $role one of the Role::* constants
208 208
 	 * @return MessageParam[] list of a single raw message param (i. e. [ Message::rawParam( … ) ])
209 209
 	 */
210
-	private function renderItemIdSnakValue( ItemIdSnakValue $value, ?string $role ): array {
211
-		switch ( true ) {
210
+	private function renderItemIdSnakValue(ItemIdSnakValue $value, ?string $role): array {
211
+		switch (true) {
212 212
 			case $value->isValue():
213
-				return $this->renderEntityId( $value->getItemId(), $role );
213
+				return $this->renderEntityId($value->getItemId(), $role);
214 214
 			case $value->isSomeValue():
215
-				return [ Message::rawParam( $this->addRole(
216
-					'<span class="wikibase-snakview-variation-somevaluesnak">' .
217
-						$this->msgEscaped( 'wikibase-snakview-snaktypeselector-somevalue' ) .
215
+				return [Message::rawParam($this->addRole(
216
+					'<span class="wikibase-snakview-variation-somevaluesnak">'.
217
+						$this->msgEscaped('wikibase-snakview-snaktypeselector-somevalue').
218 218
 						'</span>',
219 219
 					$role
220
-				) ) ];
220
+				))];
221 221
 			case $value->isNoValue():
222
-				return [ Message::rawParam( $this->addRole(
223
-					'<span class="wikibase-snakview-variation-novaluesnak">' .
224
-					$this->msgEscaped( 'wikibase-snakview-snaktypeselector-novalue' ) .
222
+				return [Message::rawParam($this->addRole(
223
+					'<span class="wikibase-snakview-variation-novaluesnak">'.
224
+					$this->msgEscaped('wikibase-snakview-snaktypeselector-novalue').
225 225
 						'</span>',
226 226
 					$role
227
-				) ) ];
227
+				))];
228 228
 			default:
229 229
 				// @codeCoverageIgnoreStart
230 230
 				throw new LogicException(
@@ -239,8 +239,8 @@  discard block
 block discarded – undo
239 239
 	 * @param string|null $role one of the Role::* constants
240 240
 	 * @return MessageParam[] list of parameters as accepted by Message::params()
241 241
 	 */
242
-	private function renderItemIdSnakValueList( array $valueList, ?string $role ): array {
243
-		return $this->renderList( $valueList, $role, [ $this, 'renderItemIdSnakValue' ] );
242
+	private function renderItemIdSnakValueList(array $valueList, ?string $role): array {
243
+		return $this->renderList($valueList, $role, [$this, 'renderItemIdSnakValue']);
244 244
 	}
245 245
 
246 246
 	/**
@@ -248,11 +248,11 @@  discard block
 block discarded – undo
248 248
 	 * @param string|null $role one of the Role::* constants
249 249
 	 * @return MessageParam[] list of parameters as accepted by Message::params()
250 250
 	 */
251
-	private function renderDataValue( DataValue $dataValue, ?string $role ): array {
252
-		return [ Message::rawParam( $this->addRole(
253
-			$this->dataValueFormatter->format( $dataValue ),
251
+	private function renderDataValue(DataValue $dataValue, ?string $role): array {
252
+		return [Message::rawParam($this->addRole(
253
+			$this->dataValueFormatter->format($dataValue),
254 254
 			$role
255
-		) ) ];
255
+		))];
256 256
 	}
257 257
 
258 258
 	/**
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
 	 * @param string|null $role one of the Role::* constants
261 261
 	 * @return MessageParam[] list of parameters as accepted by Message::params()
262 262
 	 */
263
-	private function renderDataValueType( string $dataValueType, ?string $role ): array {
263
+	private function renderDataValueType(string $dataValueType, ?string $role): array {
264 264
 		$messageKeys = [
265 265
 			'string' => 'datatypes-type-string',
266 266
 			'monolingualtext' => 'datatypes-type-monolingualtext',
@@ -269,15 +269,15 @@  discard block
 block discarded – undo
269 269
 			'wikibase-entityid' => 'wbqc-dataValueType-wikibase-entityid',
270 270
 		];
271 271
 
272
-		if ( array_key_exists( $dataValueType, $messageKeys ) ) {
273
-			return [ Message::rawParam( $this->addRole(
274
-				$this->msgEscaped( $messageKeys[$dataValueType] ),
272
+		if (array_key_exists($dataValueType, $messageKeys)) {
273
+			return [Message::rawParam($this->addRole(
274
+				$this->msgEscaped($messageKeys[$dataValueType]),
275 275
 				$role
276
-			) ) ];
276
+			))];
277 277
 		} else {
278 278
 			// @codeCoverageIgnoreStart
279 279
 			throw new LogicException(
280
-				'Unknown data value type ' . $dataValueType
280
+				'Unknown data value type '.$dataValueType
281 281
 			);
282 282
 			// @codeCoverageIgnoreEnd
283 283
 		}
@@ -288,11 +288,11 @@  discard block
 block discarded – undo
288 288
 	 * @param string|null $role one of the Role::* constants
289 289
 	 * @return MessageParam[] list of parameters as accepted by Message::params()
290 290
 	 */
291
-	private function renderInlineCode( string $code, ?string $role ): array {
292
-		return [ Message::rawParam( $this->addRole(
293
-			'<code>' . htmlspecialchars( $code ) . '</code>',
291
+	private function renderInlineCode(string $code, ?string $role): array {
292
+		return [Message::rawParam($this->addRole(
293
+			'<code>'.htmlspecialchars($code).'</code>',
294 294
 			$role
295
-		) ) ];
295
+		))];
296 296
 	}
297 297
 
298 298
 	/**
@@ -300,8 +300,8 @@  discard block
 block discarded – undo
300 300
 	 * @param string|null $role one of the Role::* constants
301 301
 	 * @return MessageParam[] list of a single raw message param (i. e. [ Message::rawParam( … ) ])
302 302
 	 */
303
-	private function renderConstraintScope( string $scope, ?string $role ): array {
304
-		switch ( $scope ) {
303
+	private function renderConstraintScope(string $scope, ?string $role): array {
304
+		switch ($scope) {
305 305
 			case Context::TYPE_STATEMENT:
306 306
 				$itemId = $this->config->get(
307 307
 					'WBQualityConstraintsConstraintCheckedOnMainValueId'
@@ -321,10 +321,10 @@  discard block
 block discarded – undo
321 321
 				// callers should never let this happen, but if it does happen,
322 322
 				// showing “unknown value” seems reasonable
323 323
 				// @codeCoverageIgnoreStart
324
-				return $this->renderItemIdSnakValue( ItemIdSnakValue::someValue(), $role );
324
+				return $this->renderItemIdSnakValue(ItemIdSnakValue::someValue(), $role);
325 325
 				// @codeCoverageIgnoreEnd
326 326
 		}
327
-		return $this->renderEntityId( new ItemId( $itemId ), $role );
327
+		return $this->renderEntityId(new ItemId($itemId), $role);
328 328
 	}
329 329
 
330 330
 	/**
@@ -332,8 +332,8 @@  discard block
 block discarded – undo
332 332
 	 * @param string|null $role one of the Role::* constants
333 333
 	 * @return MessageParam[] list of parameters as accepted by Message::params()
334 334
 	 */
335
-	private function renderConstraintScopeList( array $scopeList, ?string $role ): array {
336
-		return $this->renderList( $scopeList, $role, [ $this, 'renderConstraintScope' ] );
335
+	private function renderConstraintScopeList(array $scopeList, ?string $role): array {
336
+		return $this->renderList($scopeList, $role, [$this, 'renderConstraintScope']);
337 337
 	}
338 338
 
339 339
 	/**
@@ -341,25 +341,25 @@  discard block
 block discarded – undo
341 341
 	 * @param string|null $role one of the Role::* constants
342 342
 	 * @return MessageParam[] list of a single raw message param (i. e. [ Message::rawParam( … ) ])
343 343
 	 */
344
-	private function renderPropertyScope( string $scope, ?string $role ): array {
345
-		switch ( $scope ) {
344
+	private function renderPropertyScope(string $scope, ?string $role): array {
345
+		switch ($scope) {
346 346
 			case Context::TYPE_STATEMENT:
347
-				$itemId = $this->config->get( 'WBQualityConstraintsAsMainValueId' );
347
+				$itemId = $this->config->get('WBQualityConstraintsAsMainValueId');
348 348
 				break;
349 349
 			case Context::TYPE_QUALIFIER:
350
-				$itemId = $this->config->get( 'WBQualityConstraintsAsQualifiersId' );
350
+				$itemId = $this->config->get('WBQualityConstraintsAsQualifiersId');
351 351
 				break;
352 352
 			case Context::TYPE_REFERENCE:
353
-				$itemId = $this->config->get( 'WBQualityConstraintsAsReferencesId' );
353
+				$itemId = $this->config->get('WBQualityConstraintsAsReferencesId');
354 354
 				break;
355 355
 			default:
356 356
 				// callers should never let this happen, but if it does happen,
357 357
 				// showing “unknown value” seems reasonable
358 358
 				// @codeCoverageIgnoreStart
359
-				return $this->renderItemIdSnakValue( ItemIdSnakValue::someValue(), $role );
359
+				return $this->renderItemIdSnakValue(ItemIdSnakValue::someValue(), $role);
360 360
 				// @codeCoverageIgnoreEnd
361 361
 		}
362
-		return $this->renderEntityId( new ItemId( $itemId ), $role );
362
+		return $this->renderEntityId(new ItemId($itemId), $role);
363 363
 	}
364 364
 
365 365
 	/**
@@ -367,8 +367,8 @@  discard block
 block discarded – undo
367 367
 	 * @param string|null $role one of the Role::* constants
368 368
 	 * @return MessageParam[] list of parameters as accepted by Message::params()
369 369
 	 */
370
-	private function renderPropertyScopeList( array $scopeList, ?string $role ): array {
371
-		return $this->renderList( $scopeList, $role, [ $this, 'renderPropertyScope' ] );
370
+	private function renderPropertyScopeList(array $scopeList, ?string $role): array {
371
+		return $this->renderList($scopeList, $role, [$this, 'renderPropertyScope']);
372 372
 	}
373 373
 
374 374
 	/**
@@ -377,14 +377,14 @@  discard block
 block discarded – undo
377 377
 	 * @return MessageParam[] list of parameters as accepted by Message::params()
378 378
 	 * @suppress PhanUnusedPrivateMethodParameter
379 379
 	 */
380
-	private function renderLanguage( string $languageCode, ?string $role ): array {
380
+	private function renderLanguage(string $languageCode, ?string $role): array {
381 381
 		return [
382 382
 			// ::renderList (through ::renderLanguageList) requires 'raw' parameter
383 383
 			// so we effectively build Message::plaintextParam here
384
-			Message::rawParam( htmlspecialchars(
385
-				$this->languageNameUtils->getLanguageName( $languageCode, $this->userLanguageCode )
386
-			) ),
387
-			Message::plaintextParam( $languageCode ),
384
+			Message::rawParam(htmlspecialchars(
385
+				$this->languageNameUtils->getLanguageName($languageCode, $this->userLanguageCode)
386
+			)),
387
+			Message::plaintextParam($languageCode),
388 388
 		];
389 389
 	}
390 390
 
@@ -393,8 +393,8 @@  discard block
 block discarded – undo
393 393
 	 * @param string|null $role one of the Role::* constants
394 394
 	 * @return MessageParam[] list of parameters as accepted by Message::params()
395 395
 	 */
396
-	private function renderLanguageList( array $languageCodes, ?string $role ): array {
397
-		return $this->renderList( $languageCodes, $role, [ $this, 'renderLanguage' ] );
396
+	private function renderLanguageList(array $languageCodes, ?string $role): array {
397
+		return $this->renderList($languageCodes, $role, [$this, 'renderLanguage']);
398 398
 	}
399 399
 
400 400
 }
Please login to merge, or discard this patch.
src/ConstraintCheck/Helper/TypeCheckerHelper.php 1 patch
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -81,26 +81,26 @@  discard block
 block discarded – undo
81 81
 	 * @return bool
82 82
 	 * @throws OverflowException if $entitiesChecked exceeds the configured limit
83 83
 	 */
84
-	private function isSubclassOf( EntityId $comparativeClass, array $classesToCheck, &$entitiesChecked = 0 ) {
85
-		$maxEntities = $this->config->get( 'WBQualityConstraintsTypeCheckMaxEntities' );
84
+	private function isSubclassOf(EntityId $comparativeClass, array $classesToCheck, &$entitiesChecked = 0) {
85
+		$maxEntities = $this->config->get('WBQualityConstraintsTypeCheckMaxEntities');
86 86
 		if ( ++$entitiesChecked > $maxEntities ) {
87
-			throw new OverflowException( 'Too many entities to check' );
87
+			throw new OverflowException('Too many entities to check');
88 88
 		}
89 89
 
90
-		$item = $this->entityLookup->getEntity( $comparativeClass );
91
-		if ( !( $item instanceof StatementListProvider ) ) {
90
+		$item = $this->entityLookup->getEntity($comparativeClass);
91
+		if (!($item instanceof StatementListProvider)) {
92 92
 			return false; // lookup failed, probably because item doesn't exist
93 93
 		}
94 94
 
95
-		$subclassId = $this->config->get( 'WBQualityConstraintsSubclassOfId' );
95
+		$subclassId = $this->config->get('WBQualityConstraintsSubclassOfId');
96 96
 		$statements = $item->getStatements()
97
-			->getByPropertyId( new NumericPropertyId( $subclassId ) )
97
+			->getByPropertyId(new NumericPropertyId($subclassId))
98 98
 			->getBestStatements();
99 99
 		/** @var Statement $statement */
100
-		foreach ( $statements as $statement ) {
100
+		foreach ($statements as $statement) {
101 101
 			$mainSnak = $statement->getMainSnak();
102 102
 
103
-			if ( !$this->hasCorrectType( $mainSnak ) ) {
103
+			if (!$this->hasCorrectType($mainSnak)) {
104 104
 				continue;
105 105
 			}
106 106
 			/** @var PropertyValueSnak $mainSnak */
@@ -110,11 +110,11 @@  discard block
 block discarded – undo
110 110
 			'@phan-var EntityIdValue $dataValue';
111 111
 			$comparativeClass = $dataValue->getEntityId();
112 112
 
113
-			if ( in_array( $comparativeClass->getSerialization(), $classesToCheck ) ) {
113
+			if (in_array($comparativeClass->getSerialization(), $classesToCheck)) {
114 114
 				return true;
115 115
 			}
116 116
 
117
-			if ( $this->isSubclassOf( $comparativeClass, $classesToCheck, $entitiesChecked ) ) {
117
+			if ($this->isSubclassOf($comparativeClass, $classesToCheck, $entitiesChecked)) {
118 118
 				return true;
119 119
 			}
120 120
 		}
@@ -135,35 +135,35 @@  discard block
 block discarded – undo
135 135
 	 * @return CachedBool
136 136
 	 * @throws SparqlHelperException if SPARQL is used and the query times out or some other error occurs
137 137
 	 */
138
-	public function isSubclassOfWithSparqlFallback( EntityId $comparativeClass, array $classesToCheck ) {
139
-		$timing = $this->statsFactory->getTiming( 'isSubclassOf_duration_seconds' )
140
-			->setLabel( 'result', 'success' )
141
-			->setLabel( 'TypeCheckerImplementation', 'php' );
138
+	public function isSubclassOfWithSparqlFallback(EntityId $comparativeClass, array $classesToCheck) {
139
+		$timing = $this->statsFactory->getTiming('isSubclassOf_duration_seconds')
140
+			->setLabel('result', 'success')
141
+			->setLabel('TypeCheckerImplementation', 'php');
142 142
 		$timing->start();
143 143
 
144 144
 		try {
145 145
 			$entitiesChecked = 0;
146
-			$isSubclass = $this->isSubclassOf( $comparativeClass, $classesToCheck, $entitiesChecked );
146
+			$isSubclass = $this->isSubclassOf($comparativeClass, $classesToCheck, $entitiesChecked);
147 147
 			$timing->stop();
148 148
 
149 149
 			// not really a timing, but works like one (we want percentiles etc.)
150 150
 			// TODO: probably a good candidate for T348796
151
-			$this->statsFactory->getTiming( 'isSubclassOf_entities_total' )
152
-				->setLabel( 'TypeCheckerImplementation', 'php' )
153
-				->setLabel( 'result', 'success' )
154
-				->observe( $entitiesChecked );
155
-
156
-			return new CachedBool( $isSubclass, Metadata::blank() );
157
-		} catch ( OverflowException ) {
158
-			$timing->setLabel( 'result', 'overflow' )
151
+			$this->statsFactory->getTiming('isSubclassOf_entities_total')
152
+				->setLabel('TypeCheckerImplementation', 'php')
153
+				->setLabel('result', 'success')
154
+				->observe($entitiesChecked);
155
+
156
+			return new CachedBool($isSubclass, Metadata::blank());
157
+		} catch (OverflowException) {
158
+			$timing->setLabel('result', 'overflow')
159 159
 				->stop();
160 160
 
161
-			if ( !( $this->sparqlHelper instanceof DummySparqlHelper ) ) {
162
-				$this->statsFactory->getCounter( 'sparql_typeFallback_total' )
161
+			if (!($this->sparqlHelper instanceof DummySparqlHelper)) {
162
+				$this->statsFactory->getCounter('sparql_typeFallback_total')
163 163
 					->increment();
164 164
 
165
-				$timing->setLabel( 'TypeCheckerImplementation', 'sparql' )
166
-					->setLabel( 'result', 'success' )
165
+				$timing->setLabel('TypeCheckerImplementation', 'sparql')
166
+					->setLabel('result', 'success')
167 167
 					->start();
168 168
 
169 169
 				$hasType = $this->sparqlHelper->hasType(
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 
176 176
 				return $hasType;
177 177
 			} else {
178
-				return new CachedBool( false, Metadata::blank() );
178
+				return new CachedBool(false, Metadata::blank());
179 179
 			}
180 180
 		}
181 181
 	}
@@ -193,13 +193,13 @@  discard block
 block discarded – undo
193 193
 	 * @return CachedBool
194 194
 	 * @throws SparqlHelperException if SPARQL is used and the query times out or some other error occurs
195 195
 	 */
196
-	public function hasClassInRelation( StatementList $statements, array $relationIds, array $classesToCheck ) {
196
+	public function hasClassInRelation(StatementList $statements, array $relationIds, array $classesToCheck) {
197 197
 		$metadatas = [];
198 198
 
199
-		foreach ( $this->getBestStatementsByPropertyIds( $statements, $relationIds ) as $statement ) {
199
+		foreach ($this->getBestStatementsByPropertyIds($statements, $relationIds) as $statement) {
200 200
 			$mainSnak = $statement->getMainSnak();
201 201
 
202
-			if ( !$this->hasCorrectType( $mainSnak ) ) {
202
+			if (!$this->hasCorrectType($mainSnak)) {
203 203
 				continue;
204 204
 			}
205 205
 			/** @var PropertyValueSnak $mainSnak */
@@ -209,24 +209,24 @@  discard block
 block discarded – undo
209 209
 			'@phan-var EntityIdValue $dataValue';
210 210
 			$comparativeClass = $dataValue->getEntityId();
211 211
 
212
-			if ( in_array( $comparativeClass->getSerialization(), $classesToCheck ) ) {
212
+			if (in_array($comparativeClass->getSerialization(), $classesToCheck)) {
213 213
 				// discard $metadatas, we know this is fresh
214
-				return new CachedBool( true, Metadata::blank() );
214
+				return new CachedBool(true, Metadata::blank());
215 215
 			}
216 216
 
217
-			$result = $this->isSubclassOfWithSparqlFallback( $comparativeClass, $classesToCheck );
217
+			$result = $this->isSubclassOfWithSparqlFallback($comparativeClass, $classesToCheck);
218 218
 			$metadatas[] = $result->getMetadata();
219
-			if ( $result->getBool() ) {
219
+			if ($result->getBool()) {
220 220
 				return new CachedBool(
221 221
 					true,
222
-					Metadata::merge( $metadatas )
222
+					Metadata::merge($metadatas)
223 223
 				);
224 224
 			}
225 225
 		}
226 226
 
227 227
 		return new CachedBool(
228 228
 			false,
229
-			Metadata::merge( $metadatas )
229
+			Metadata::merge($metadatas)
230 230
 		);
231 231
 	}
232 232
 
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 	 * @return bool
236 236
 	 * @phan-assert PropertyValueSnak $mainSnak
237 237
 	 */
238
-	private function hasCorrectType( Snak $mainSnak ) {
238
+	private function hasCorrectType(Snak $mainSnak) {
239 239
 		return $mainSnak instanceof PropertyValueSnak
240 240
 			&& $mainSnak->getDataValue()->getType() === 'wikibase-entityid';
241 241
 	}
@@ -252,15 +252,15 @@  discard block
 block discarded – undo
252 252
 	) {
253 253
 		$statementArrays = [];
254 254
 
255
-		foreach ( $propertyIdSerializations as $propertyIdSerialization ) {
256
-			$propertyId = new NumericPropertyId( $propertyIdSerialization );
255
+		foreach ($propertyIdSerializations as $propertyIdSerialization) {
256
+			$propertyId = new NumericPropertyId($propertyIdSerialization);
257 257
 			$statementArrays[] = $statements
258
-				->getByPropertyId( $propertyId )
258
+				->getByPropertyId($propertyId)
259 259
 				->getBestStatements()
260 260
 				->toArray();
261 261
 		}
262 262
 
263
-		return array_merge( ...$statementArrays );
263
+		return array_merge(...$statementArrays);
264 264
 	}
265 265
 
266 266
 	/**
@@ -280,8 +280,8 @@  discard block
 block discarded – undo
280 280
 		$relation
281 281
 	) {
282 282
 		$classes = array_map(
283
-			static function ( $itemIdSerialization ) {
284
-				return new ItemId( $itemIdSerialization );
283
+			static function($itemIdSerialization) {
284
+				return new ItemId($itemIdSerialization);
285 285
 			},
286 286
 			$classes
287 287
 		);
@@ -293,10 +293,10 @@  discard block
 block discarded – undo
293 293
 		// wbqc-violation-message-valueType-instance
294 294
 		// wbqc-violation-message-valueType-subclass
295 295
 		// wbqc-violation-message-valueType-instanceOrSubclass
296
-		return ( new ViolationMessage( 'wbqc-violation-message-' . $checker . '-' . $relation ) )
297
-			->withEntityId( $propertyId, Role::CONSTRAINT_PROPERTY )
298
-			->withEntityId( $entityId, Role::SUBJECT )
299
-			->withEntityIdList( $classes, Role::OBJECT );
296
+		return (new ViolationMessage('wbqc-violation-message-'.$checker.'-'.$relation))
297
+			->withEntityId($propertyId, Role::CONSTRAINT_PROPERTY)
298
+			->withEntityId($entityId, Role::SUBJECT)
299
+			->withEntityIdList($classes, Role::OBJECT);
300 300
 	}
301 301
 
302 302
 }
Please login to merge, or discard this patch.
src/ConstraintCheck/Helper/LoggingHelper.php 1 patch
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -53,12 +53,12 @@  discard block
 block discarded – undo
53 53
 		$this->statsFactory = $statsFactory;
54 54
 		$this->logger = $logger;
55 55
 		$this->constraintCheckDurationLimits = [
56
-			'info' => $config->get( 'WBQualityConstraintsCheckDurationInfoSeconds' ),
57
-			'warning' => $config->get( 'WBQualityConstraintsCheckDurationWarningSeconds' ),
56
+			'info' => $config->get('WBQualityConstraintsCheckDurationInfoSeconds'),
57
+			'warning' => $config->get('WBQualityConstraintsCheckDurationWarningSeconds'),
58 58
 		];
59 59
 		$this->constraintCheckOnEntityDurationLimits = [
60
-			'info' => $config->get( 'WBQualityConstraintsCheckOnEntityDurationInfoSeconds' ),
61
-			'warning' => $config->get( 'WBQualityConstraintsCheckOnEntityDurationWarningSeconds' ),
60
+			'info' => $config->get('WBQualityConstraintsCheckOnEntityDurationInfoSeconds'),
61
+			'warning' => $config->get('WBQualityConstraintsCheckOnEntityDurationWarningSeconds'),
62 62
 		];
63 63
 	}
64 64
 
@@ -70,23 +70,23 @@  discard block
 block discarded – undo
70 70
 	 * @param float $durationSeconds
71 71
 	 * @return array [ $limitSeconds, $logLevel ]
72 72
 	 */
73
-	private function findLimit( $limits, $durationSeconds ) {
73
+	private function findLimit($limits, $durationSeconds) {
74 74
 		$limitSeconds = null;
75 75
 		$logLevel = null;
76 76
 
77
-		foreach ( $limits as $level => $limit ) {
77
+		foreach ($limits as $level => $limit) {
78 78
 			if (
79 79
 				// duration exceeds this limit
80 80
 				$limit !== null && $durationSeconds > $limit &&
81 81
 				// this limit is longer than previous longest limit
82
-				( $limitSeconds === null || $limit > $limitSeconds )
82
+				($limitSeconds === null || $limit > $limitSeconds)
83 83
 			) {
84 84
 				$limitSeconds = $limit;
85 85
 				$logLevel = $level;
86 86
 			}
87 87
 		}
88 88
 
89
-		return [ $limitSeconds, $logLevel ];
89
+		return [$limitSeconds, $logLevel];
90 90
 	}
91 91
 
92 92
 	/**
@@ -111,27 +111,27 @@  discard block
 block discarded – undo
111 111
 		$durationSeconds,
112 112
 		$method
113 113
 	) {
114
-		$constraintCheckerClassShortName = substr( strrchr( $constraintCheckerClass, '\\' ), 1 );
114
+		$constraintCheckerClassShortName = substr(strrchr($constraintCheckerClass, '\\'), 1);
115 115
 		$constraintTypeItemId = $constraint->getConstraintTypeItemId();
116 116
 
117
-		$this->statsFactory->getTiming( 'check_constraint_duration_seconds' )
118
-			->observe( $durationSeconds * 1000 );
117
+		$this->statsFactory->getTiming('check_constraint_duration_seconds')
118
+			->observe($durationSeconds * 1000);
119 119
 
120 120
 		// find the longest limit (and associated log level) that the duration exceeds
121
-		[ $limitSeconds, $logLevel ] = $this->findLimit(
121
+		[$limitSeconds, $logLevel] = $this->findLimit(
122 122
 			$this->constraintCheckDurationLimits,
123 123
 			$durationSeconds
124 124
 		);
125
-		if ( $limitSeconds === null ) {
125
+		if ($limitSeconds === null) {
126 126
 			return;
127 127
 		}
128
-		if ( $context->getType() !== Context::TYPE_STATEMENT ) {
128
+		if ($context->getType() !== Context::TYPE_STATEMENT) {
129 129
 			// TODO log less details but still log something
130 130
 			return;
131 131
 		}
132 132
 
133 133
 		$resultMessage = $result->getMessage();
134
-		if ( $resultMessage !== null ) {
134
+		if ($resultMessage !== null) {
135 135
 			$resultMessageKey = $resultMessage->getMessageKey();
136 136
 		} else {
137 137
 			$resultMessageKey = null;
@@ -139,8 +139,8 @@  discard block
 block discarded – undo
139 139
 
140 140
 		$this->logger->log(
141 141
 			$logLevel,
142
-			'Constraint check with {constraintCheckerClassShortName} ' .
143
-			'took longer than {limitSeconds} second(s) ' .
142
+			'Constraint check with {constraintCheckerClassShortName} '.
143
+			'took longer than {limitSeconds} second(s) '.
144 144
 			'(duration: {durationSeconds} seconds).',
145 145
 			[
146 146
 				'method' => $method,
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 				'constraintId' => $constraint->getConstraintId(),
151 151
 				'constraintPropertyId' => $constraint->getPropertyId()->getSerialization(),
152 152
 				'constraintTypeItemId' => $constraintTypeItemId,
153
-				'constraintParameters' => json_encode( $constraint->getConstraintParameters() ),
153
+				'constraintParameters' => json_encode($constraint->getConstraintParameters()),
154 154
 				'constraintCheckerClass' => $constraintCheckerClass,
155 155
 				'constraintCheckerClassShortName' => $constraintCheckerClassShortName,
156 156
 				'entityId' => $context->getEntity()->getId()->getSerialization(),
@@ -180,22 +180,22 @@  discard block
 block discarded – undo
180 180
 		$durationSeconds,
181 181
 		$method
182 182
 	) {
183
-		$this->statsFactory->getTiming( 'check_entity_constraint_duration_seconds' )
184
-			->observe( $durationSeconds * 1000 );
183
+		$this->statsFactory->getTiming('check_entity_constraint_duration_seconds')
184
+			->observe($durationSeconds * 1000);
185 185
 
186 186
 		// find the longest limit (and associated log level) that the duration exceeds
187
-		[ $limitSeconds, $logLevel ] = $this->findLimit(
187
+		[$limitSeconds, $logLevel] = $this->findLimit(
188 188
 			$this->constraintCheckOnEntityDurationLimits,
189 189
 			$durationSeconds
190 190
 		);
191
-		if ( $limitSeconds === null ) {
191
+		if ($limitSeconds === null) {
192 192
 			return;
193 193
 		}
194 194
 
195 195
 		$this->logger->log(
196 196
 			$logLevel,
197
-			'Full constraint check on {entityId} ' .
198
-			'took longer than {limitSeconds} second(s) ' .
197
+			'Full constraint check on {entityId} '.
198
+			'took longer than {limitSeconds} second(s) '.
199 199
 			'(duration: {durationSeconds} seconds).',
200 200
 			[
201 201
 				'method' => $method,
@@ -211,8 +211,8 @@  discard block
 block discarded – undo
211 211
 	/**
212 212
 	 * Log a cache hit for a complete constraint check result for the given entity ID.
213 213
 	 */
214
-	public function logCheckConstraintsCacheHit( EntityId $entityId ) {
215
-		$this->statsFactory->getCounter( 'cache_entity_hit_total' )
214
+	public function logCheckConstraintsCacheHit(EntityId $entityId) {
215
+		$this->statsFactory->getCounter('cache_entity_hit_total')
216 216
 			->increment();
217 217
 	}
218 218
 
@@ -221,9 +221,9 @@  discard block
 block discarded – undo
221 221
 	 *
222 222
 	 * @param EntityId[] $entityIds
223 223
 	 */
224
-	public function logCheckConstraintsCacheMisses( array $entityIds ) {
225
-		$this->statsFactory->getCounter( 'cache_entity_miss_total' )
226
-			->incrementBy( count( $entityIds ) );
224
+	public function logCheckConstraintsCacheMisses(array $entityIds) {
225
+		$this->statsFactory->getCounter('cache_entity_miss_total')
226
+			->incrementBy(count($entityIds));
227 227
 	}
228 228
 
229 229
 	/**
@@ -249,17 +249,17 @@  discard block
 block discarded – undo
249 249
 	 * @param EntityId[] $entityIds
250 250
 	 * @param int $maxRevisionIds
251 251
 	 */
252
-	public function logHugeDependencyMetadata( array $entityIds, $maxRevisionIds ) {
252
+	public function logHugeDependencyMetadata(array $entityIds, $maxRevisionIds) {
253 253
 		$this->logger->log(
254 254
 			'warning',
255
-			'Dependency metadata for constraint check result has huge set of entity IDs ' .
256
-			'(count ' . count( $entityIds ) . ', limit ' . $maxRevisionIds . '); ' .
255
+			'Dependency metadata for constraint check result has huge set of entity IDs '.
256
+			'(count '.count($entityIds).', limit '.$maxRevisionIds.'); '.
257 257
 			'caching disabled for this check result.',
258 258
 			[
259 259
 				'loggingMethod' => __METHOD__,
260 260
 				'entityIds' => json_encode(
261 261
 					array_map(
262
-						static function ( EntityId $entityId ) {
262
+						static function(EntityId $entityId) {
263 263
 							return $entityId->getSerialization();
264 264
 						},
265 265
 						$entityIds
@@ -278,17 +278,17 @@  discard block
 block discarded – undo
278 278
 			'Sparql API replied with status 429 and a retry-after header. Requesting to retry after {retryAfterTime}',
279 279
 			[
280 280
 				'retryAfterTime' => $retryAfterTime,
281
-				'responseHeaders' => json_encode( $request->getResponseHeaders() ),
281
+				'responseHeaders' => json_encode($request->getResponseHeaders()),
282 282
 				'responseContent' => $request->getContent(),
283 283
 			]
284 284
 		);
285 285
 	}
286 286
 
287
-	public function logSparqlHelperTooManyRequestsRetryAfterInvalid( MWHttpRequest $request ) {
287
+	public function logSparqlHelperTooManyRequestsRetryAfterInvalid(MWHttpRequest $request) {
288 288
 		$this->logger->warning(
289 289
 			'Sparql API replied with status 429 and no valid retry-after header.',
290 290
 			[
291
-				'responseHeaders' => json_encode( $request->getResponseHeaders() ),
291
+				'responseHeaders' => json_encode($request->getResponseHeaders()),
292 292
 				'responseContent' => $request->getContent(),
293 293
 			]
294 294
 		);
Please login to merge, or discard this patch.
src/ConstraintCheck/Helper/SparqlHelper.php 1 patch
Spacing   +212 added lines, -216 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare( strict_types = 1 );
3
+declare(strict_types=1);
4 4
 
5 5
 namespace WikibaseQuality\ConstraintReport\ConstraintCheck\Helper;
6 6
 
@@ -166,143 +166,143 @@  discard block
 block discarded – undo
166 166
 		$this->defaultUserAgent = $defaultUserAgent;
167 167
 		$this->requestFactory = $requestFactory;
168 168
 		$this->entityPrefixes = [];
169
-		foreach ( $rdfVocabulary->entityNamespaceNames as $namespaceName ) {
170
-			$this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI( $namespaceName );
169
+		foreach ($rdfVocabulary->entityNamespaceNames as $namespaceName) {
170
+			$this->entityPrefixes[] = $rdfVocabulary->getNamespaceURI($namespaceName);
171 171
 		}
172 172
 
173
-		$this->primaryEndpoint = $config->get( 'WBQualityConstraintsSparqlEndpoint' );
174
-		$this->additionalEndpoints = $config->get( 'WBQualityConstraintsAdditionalSparqlEndpoints' ) ?: [];
175
-		$this->maxQueryTimeMillis = $config->get( 'WBQualityConstraintsSparqlMaxMillis' );
176
-		$this->subclassOfId = new NumericPropertyId( $config->get( 'WBQualityConstraintsSubclassOfId' ) );
177
-		$this->cacheMapSize = $config->get( 'WBQualityConstraintsFormatCacheMapSize' );
173
+		$this->primaryEndpoint = $config->get('WBQualityConstraintsSparqlEndpoint');
174
+		$this->additionalEndpoints = $config->get('WBQualityConstraintsAdditionalSparqlEndpoints') ?: [];
175
+		$this->maxQueryTimeMillis = $config->get('WBQualityConstraintsSparqlMaxMillis');
176
+		$this->subclassOfId = new NumericPropertyId($config->get('WBQualityConstraintsSubclassOfId'));
177
+		$this->cacheMapSize = $config->get('WBQualityConstraintsFormatCacheMapSize');
178 178
 		$this->timeoutExceptionClasses = $config->get(
179 179
 			'WBQualityConstraintsSparqlTimeoutExceptionClasses'
180 180
 		);
181 181
 		$this->sparqlHasWikibaseSupport = $config->get(
182 182
 			'WBQualityConstraintsSparqlHasWikibaseSupport'
183 183
 		);
184
-		$this->sparqlThrottlingFallbackDuration = (int)$config->get(
184
+		$this->sparqlThrottlingFallbackDuration = (int) $config->get(
185 185
 			'WBQualityConstraintsSparqlThrottlingFallbackDuration'
186 186
 		);
187 187
 
188
-		$this->prefixes = $this->getQueryPrefixes( $rdfVocabulary );
188
+		$this->prefixes = $this->getQueryPrefixes($rdfVocabulary);
189 189
 
190 190
 		$this->rdfVocabularyWithoutNormalization = clone $rdfVocabulary;
191 191
 		// @phan-suppress-next-line PhanTypeMismatchProperty
192 192
 		$this->rdfVocabularyWithoutNormalization->normalizedPropertyValueNamespace = array_fill_keys(
193
-			array_keys( $rdfVocabulary->normalizedPropertyValueNamespace ),
193
+			array_keys($rdfVocabulary->normalizedPropertyValueNamespace),
194 194
 			null
195 195
 		);
196 196
 	}
197 197
 
198
-	private function getQueryPrefixes( RdfVocabulary $rdfVocabulary ): string {
198
+	private function getQueryPrefixes(RdfVocabulary $rdfVocabulary): string {
199 199
 		// TODO: it would probably be smarter that RdfVocabulary exposed these prefixes somehow
200 200
 		$prefixes = '';
201
-		foreach ( $rdfVocabulary->entityNamespaceNames as $sourceName => $namespaceName ) {
201
+		foreach ($rdfVocabulary->entityNamespaceNames as $sourceName => $namespaceName) {
202 202
 			$prefixes .= <<<END
203
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
203
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
204 204
 END;
205 205
 		}
206 206
 
207
-		foreach ( $rdfVocabulary->statementNamespaceNames as $sourceName => $sourceNamespaces ) {
207
+		foreach ($rdfVocabulary->statementNamespaceNames as $sourceName => $sourceNamespaces) {
208 208
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NS_VALUE];
209 209
 			$prefixes .= <<<END
210
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
210
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
211 211
 END;
212 212
 		}
213 213
 
214
-		foreach ( $rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces ) {
214
+		foreach ($rdfVocabulary->propertyNamespaceNames as $sourceName => $sourceNamespaces) {
215 215
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_DIRECT_CLAIM];
216 216
 			$prefixes .= <<<END
217
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
217
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
218 218
 END;
219 219
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM];
220 220
 			$prefixes .= <<<END
221
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
221
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
222 222
 END;
223 223
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM_STATEMENT];
224 224
 			$prefixes .= <<<END
225
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
225
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
226 226
 END;
227 227
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_CLAIM_VALUE];
228 228
 			$prefixes .= <<<END
229
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
229
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
230 230
 END;
231 231
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER];
232 232
 			$prefixes .= <<<END
233
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
233
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
234 234
 END;
235 235
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_QUALIFIER_VALUE];
236 236
 			$prefixes .= <<<END
237
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
237
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
238 238
 END;
239 239
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE];
240 240
 			$prefixes .= <<<END
241
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
241
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
242 242
 END;
243 243
 			$namespaceName = $sourceNamespaces[RdfVocabulary::NSP_REFERENCE_VALUE];
244 244
 			$prefixes .= <<<END
245
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
245
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
246 246
 END;
247 247
 		}
248 248
 		$namespaceName = RdfVocabulary::NS_ONTOLOGY;
249 249
 		$prefixes .= <<<END
250
-PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI( $namespaceName )}>\n
250
+PREFIX {$namespaceName}: <{$rdfVocabulary->getNamespaceURI($namespaceName)}>\n
251 251
 END;
252 252
 		return $prefixes;
253 253
 	}
254 254
 
255 255
 	/** Return a SPARQL term like `wd:Q123` for the given ID. */
256
-	private function wd( EntityId $id ): string {
257
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
256
+	private function wd(EntityId $id): string {
257
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
258 258
 		$prefix = $this->rdfVocabulary->entityNamespaceNames[$repository];
259 259
 		return "$prefix:{$id->getSerialization()}";
260 260
 	}
261 261
 
262 262
 	/** Return a SPARQL term like `wdt:P123` for the given ID. */
263
-	private function wdt( PropertyId $id ): string {
264
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
263
+	private function wdt(PropertyId $id): string {
264
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
265 265
 		$prefix = $this->rdfVocabulary->propertyNamespaceNames[$repository][RdfVocabulary::NSP_DIRECT_CLAIM];
266 266
 		return "$prefix:{$id->getSerialization()}";
267 267
 	}
268 268
 
269 269
 	/** Return a SPARQL term like `p:P123` for the given ID. */
270
-	private function p( PropertyId $id ): string {
271
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
270
+	private function p(PropertyId $id): string {
271
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
272 272
 		$prefix = $this->rdfVocabulary->propertyNamespaceNames[$repository][RdfVocabulary::NSP_CLAIM];
273 273
 		return "$prefix:{$id->getSerialization()}";
274 274
 	}
275 275
 
276 276
 	/** Return a SPARQL term like `pq:P123` for the given ID. */
277
-	private function pq( PropertyId $id ): string {
278
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
277
+	private function pq(PropertyId $id): string {
278
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
279 279
 		$prefix = $this->rdfVocabulary->propertyNamespaceNames[$repository][RdfVocabulary::NSP_QUALIFIER];
280 280
 		return "$prefix:{$id->getSerialization()}";
281 281
 	}
282 282
 
283 283
 	/** Return a SPARQL term like `wdno:P123` for the given ID. */
284
-	private function wdno( PropertyId $id ): string {
285
-		$repository = $this->rdfVocabulary->getEntityRepositoryName( $id );
284
+	private function wdno(PropertyId $id): string {
285
+		$repository = $this->rdfVocabulary->getEntityRepositoryName($id);
286 286
 		$prefix = $this->rdfVocabulary->propertyNamespaceNames[$repository][RdfVocabulary::NSP_NOVALUE];
287 287
 		return "$prefix:{$id->getSerialization()}";
288 288
 	}
289 289
 
290 290
 	/** Return a SPARQL term like `prov:NAME` for the given name. */
291
-	private function prov( string $name ): string {
291
+	private function prov(string $name): string {
292 292
 		$prefix = RdfVocabulary::NS_PROV;
293 293
 		return "$prefix:$name";
294 294
 	}
295 295
 
296 296
 	/** Return a SPARQL term like `wikibase:NAME` for the given name. */
297
-	private function wikibase( string $name ): string {
297
+	private function wikibase(string $name): string {
298 298
 		$prefix = RdfVocabulary::NS_ONTOLOGY;
299 299
 		return "$prefix:$name";
300 300
 	}
301 301
 
302 302
 	/** Return a SPARQL snippet like `MINUS { ?var wikibase:rank wikibase:DeprecatedRank. }`. */
303
-	private function minusDeprecatedRank( string $varName ): string {
303
+	private function minusDeprecatedRank(string $varName): string {
304 304
 		$deprecatedRank = RdfVocabulary::RANK_MAP[Statement::RANK_DEPRECATED];
305
-		return "MINUS { $varName {$this->wikibase( 'rank' )} {$this->wikibase( $deprecatedRank )}. }";
305
+		return "MINUS { $varName {$this->wikibase('rank')} {$this->wikibase($deprecatedRank)}. }";
306 306
 	}
307 307
 
308 308
 	/**
@@ -312,43 +312,42 @@  discard block
 block discarded – undo
312 312
 	 * @return CachedBool
313 313
 	 * @throws SparqlHelperException if the query times out or some other error occurs
314 314
 	 */
315
-	public function hasType( EntityId $id, array $classes ): CachedBool {
315
+	public function hasType(EntityId $id, array $classes): CachedBool {
316 316
 		// TODO hint:gearing is a workaround for T168973 and can hopefully be removed eventually
317 317
 		$gearingHint = $this->sparqlHasWikibaseSupport ?
318
-			' hint:Prior hint:gearing "forward".' :
319
-			'';
318
+			' hint:Prior hint:gearing "forward".' : '';
320 319
 
321 320
 		$metadatas = [];
322 321
 
323
-		foreach ( array_chunk( $classes, 20 ) as $classesChunk ) {
324
-			$classesValues = implode( ' ', array_map(
325
-				function ( string $class ) {
326
-					return $this->wd( new ItemId( $class ) );
322
+		foreach (array_chunk($classes, 20) as $classesChunk) {
323
+			$classesValues = implode(' ', array_map(
324
+				function(string $class) {
325
+					return $this->wd(new ItemId($class));
327 326
 				},
328 327
 				$classesChunk
329
-			) );
328
+			));
330 329
 
331 330
 			$query = <<<EOF
332 331
 ASK {
333
-  BIND({$this->wd( $id )} AS ?item)
332
+  BIND({$this->wd($id)} AS ?item)
334 333
   VALUES ?class { $classesValues }
335
-  ?item {$this->wdt( $this->subclassOfId )}* ?class.$gearingHint
334
+  ?item {$this->wdt($this->subclassOfId)}* ?class.$gearingHint
336 335
 }
337 336
 EOF;
338 337
 
339
-			$result = $this->runQuery( $query, $this->primaryEndpoint );
338
+			$result = $this->runQuery($query, $this->primaryEndpoint);
340 339
 			$metadatas[] = $result->getMetadata();
341
-			if ( $result->getArray()['boolean'] ) {
340
+			if ($result->getArray()['boolean']) {
342 341
 				return new CachedBool(
343 342
 					true,
344
-					Metadata::merge( $metadatas )
343
+					Metadata::merge($metadatas)
345 344
 				);
346 345
 			}
347 346
 		}
348 347
 
349 348
 		return new CachedBool(
350 349
 			false,
351
-			Metadata::merge( $metadatas )
350
+			Metadata::merge($metadatas)
352 351
 		);
353 352
 	}
354 353
 
@@ -366,12 +365,12 @@  discard block
 block discarded – undo
366 365
 		array $separators
367 366
 	): CachedEntityIds {
368 367
 		$mainSnak = $statement->getMainSnak();
369
-		if ( !( $mainSnak instanceof PropertyValueSnak ) ) {
370
-			return new CachedEntityIds( [], Metadata::blank() );
368
+		if (!($mainSnak instanceof PropertyValueSnak)) {
369
+			return new CachedEntityIds([], Metadata::blank());
371 370
 		}
372 371
 
373 372
 		$propertyId = $statement->getPropertyId();
374
-		$pPredicateAndObject = "{$this->p( $propertyId )} ?otherStatement."; // p:P123 ?otherStatement.
373
+		$pPredicateAndObject = "{$this->p($propertyId)} ?otherStatement."; // p:P123 ?otherStatement.
375 374
 		$otherStatementPredicateAndObject = $this->getSnakPredicateAndObject(
376 375
 			$entityId,
377 376
 			$mainSnak,
@@ -380,57 +379,57 @@  discard block
 block discarded – undo
380 379
 
381 380
 		$isSeparator = [];
382 381
 		$unusedSeparators = [];
383
-		foreach ( $separators as $separator ) {
382
+		foreach ($separators as $separator) {
384 383
 			$isSeparator[$separator->getSerialization()] = true;
385 384
 			$unusedSeparators[$separator->getSerialization()] = $separator;
386 385
 		}
387 386
 		$separatorFilters = '';
388
-		foreach ( $statement->getQualifiers() as $qualifier ) {
387
+		foreach ($statement->getQualifiers() as $qualifier) {
389 388
 			$qualPropertyId = $qualifier->getPropertyId();
390
-			if ( !( $isSeparator[$qualPropertyId->getSerialization()] ?? false ) ) {
389
+			if (!($isSeparator[$qualPropertyId->getSerialization()] ?? false)) {
391 390
 				continue;
392 391
 			}
393
-			unset( $unusedSeparators[$qualPropertyId->getSerialization()] );
392
+			unset($unusedSeparators[$qualPropertyId->getSerialization()]);
394 393
 			// only look for other statements with the same qualifier
395
-			if ( $qualifier instanceof PropertyValueSnak ) {
394
+			if ($qualifier instanceof PropertyValueSnak) {
396 395
 				$sepPredicateAndObject = $this->getSnakPredicateAndObject(
397 396
 					$entityId,
398 397
 					$qualifier,
399 398
 					RdfVocabulary::NSP_QUALIFIER
400 399
 				);
401 400
 				$separatorFilters .= "  ?otherStatement $sepPredicateAndObject\n";
402
-			} elseif ( $qualifier instanceof PropertyNoValueSnak ) {
403
-				$sepPredicateAndObject = "a {$this->wdno( $qualPropertyId )}."; // a wdno:P123.
401
+			} elseif ($qualifier instanceof PropertyNoValueSnak) {
402
+				$sepPredicateAndObject = "a {$this->wdno($qualPropertyId)}."; // a wdno:P123.
404 403
 				$separatorFilters .= "  ?otherStatement $sepPredicateAndObject\n";
405 404
 			} else {
406 405
 				// "some value" / "unknown value" is always different from everything else,
407 406
 				// therefore the whole statement has no duplicates and we can return immediately
408
-				return new CachedEntityIds( [], Metadata::blank() );
407
+				return new CachedEntityIds([], Metadata::blank());
409 408
 			}
410 409
 		}
411
-		foreach ( $unusedSeparators as $unusedSeparator ) {
410
+		foreach ($unusedSeparators as $unusedSeparator) {
412 411
 			// exclude other statements which have a separator that this one lacks
413
-			$separatorFilters .= "  MINUS { ?otherStatement {$this->pq( $unusedSeparator )} []. }\n";
414
-			$separatorFilters .= "  MINUS { ?otherStatement a {$this->wdno( $unusedSeparator )}. }\n";
412
+			$separatorFilters .= "  MINUS { ?otherStatement {$this->pq($unusedSeparator)} []. }\n";
413
+			$separatorFilters .= "  MINUS { ?otherStatement a {$this->wdno($unusedSeparator)}. }\n";
415 414
 		}
416 415
 
417 416
 		$query = <<<SPARQL
418 417
 SELECT DISTINCT ?otherEntity WHERE {
419 418
   ?otherEntity $pPredicateAndObject
420 419
   ?otherStatement $otherStatementPredicateAndObject
421
-  {$this->minusDeprecatedRank( '?otherStatement' )}
422
-  FILTER(?otherEntity != {$this->wd( $entityId )})
420
+  {$this->minusDeprecatedRank('?otherStatement')}
421
+  FILTER(?otherEntity != {$this->wd($entityId)})
423 422
 $separatorFilters
424 423
 }
425 424
 LIMIT 10
426 425
 SPARQL;
427 426
 
428
-		$results = [ $this->runQuery( $query, $this->primaryEndpoint ) ];
429
-		foreach ( $this->additionalEndpoints as $endpoint ) {
430
-			$results[] = $this->runQuery( $query, $endpoint );
427
+		$results = [$this->runQuery($query, $this->primaryEndpoint)];
428
+		foreach ($this->additionalEndpoints as $endpoint) {
429
+			$results[] = $this->runQuery($query, $endpoint);
431 430
 		}
432 431
 
433
-		return $this->getOtherEntities( $results );
432
+		return $this->getOtherEntities($results);
434 433
 	}
435 434
 
436 435
 	/**
@@ -449,40 +448,38 @@  discard block
 block discarded – undo
449 448
 		bool $ignoreDeprecatedStatements
450 449
 	): CachedEntityIds {
451 450
 		$propertyId = $snak->getPropertyId();
452
-		$pPredicateAndObject = "{$this->p( $propertyId )} ?otherStatement."; // p:P123 ?otherStatement.
451
+		$pPredicateAndObject = "{$this->p($propertyId)} ?otherStatement."; // p:P123 ?otherStatement.
453 452
 
454 453
 		$otherSubject = $type === Context::TYPE_QUALIFIER ?
455
-			'?otherStatement' :
456
-			"?otherStatement {$this->prov( 'wasDerivedFrom' )} ?reference.\n  ?reference";
454
+			'?otherStatement' : "?otherStatement {$this->prov('wasDerivedFrom')} ?reference.\n  ?reference";
457 455
 		$otherPredicateAndObject = $this->getSnakPredicateAndObject(
458 456
 			$entityId,
459 457
 			$snak,
460 458
 			$type === Context::TYPE_QUALIFIER ?
461
-				RdfVocabulary::NSP_QUALIFIER :
462
-				RdfVocabulary::NSP_REFERENCE
459
+				RdfVocabulary::NSP_QUALIFIER : RdfVocabulary::NSP_REFERENCE
463 460
 		);
464 461
 
465 462
 		$deprecatedFilter = '';
466
-		if ( $ignoreDeprecatedStatements ) {
467
-			$deprecatedFilter = '  ' . $this->minusDeprecatedRank( '?otherStatement' );
463
+		if ($ignoreDeprecatedStatements) {
464
+			$deprecatedFilter = '  '.$this->minusDeprecatedRank('?otherStatement');
468 465
 		}
469 466
 
470 467
 		$query = <<<SPARQL
471 468
 SELECT DISTINCT ?otherEntity WHERE {
472 469
   ?otherEntity $pPredicateAndObject
473 470
   $otherSubject $otherPredicateAndObject
474
-  FILTER(?otherEntity != {$this->wd( $entityId )})
471
+  FILTER(?otherEntity != {$this->wd($entityId)})
475 472
 $deprecatedFilter
476 473
 }
477 474
 LIMIT 10
478 475
 SPARQL;
479 476
 
480
-		$results = [ $this->runQuery( $query, $this->primaryEndpoint ) ];
481
-		foreach ( $this->additionalEndpoints as $endpoint ) {
482
-			$results[] = $this->runQuery( $query, $endpoint );
477
+		$results = [$this->runQuery($query, $this->primaryEndpoint)];
478
+		foreach ($this->additionalEndpoints as $endpoint) {
479
+			$results[] = $this->runQuery($query, $endpoint);
483 480
 		}
484 481
 
485
-		return $this->getOtherEntities( $results );
482
+		return $this->getOtherEntities($results);
486 483
 	}
487 484
 
488 485
 	/**
@@ -513,13 +510,13 @@  discard block
 block discarded – undo
513 510
 		$writer->start();
514 511
 		$writer->drain();
515 512
 		$placeholder1 = 'wbqc';
516
-		$placeholder2 = 'x' . wfRandomString( 32 );
517
-		$writer->about( $placeholder1, $placeholder2 );
513
+		$placeholder2 = 'x'.wfRandomString(32);
514
+		$writer->about($placeholder1, $placeholder2);
518 515
 
519 516
 		$propertyId = $snak->getPropertyId();
520 517
 		$pid = $propertyId->getSerialization();
521
-		$propertyRepository = $this->rdfVocabulary->getEntityRepositoryName( $propertyId );
522
-		$entityRepository = $this->rdfVocabulary->getEntityRepositoryName( $entityId );
518
+		$propertyRepository = $this->rdfVocabulary->getEntityRepositoryName($propertyId);
519
+		$entityRepository = $this->rdfVocabulary->getEntityRepositoryName($entityId);
523 520
 		$propertyNamespace = $this->rdfVocabulary->propertyNamespaceNames[$propertyRepository][$namespace];
524 521
 		$value = $snak->getDataValue();
525 522
 		if (
@@ -550,21 +547,21 @@  discard block
 block discarded – undo
550 547
 				$writer,
551 548
 				$propertyNamespace,
552 549
 				$pid,
553
-				$this->propertyDataTypeLookup->getDataTypeIdForProperty( $propertyId ),
550
+				$this->propertyDataTypeLookup->getDataTypeIdForProperty($propertyId),
554 551
 				$this->rdfVocabulary->statementNamespaceNames[$entityRepository][RdfVocabulary::NS_VALUE], // should be unused
555 552
 				$snak
556 553
 			);
557 554
 		}
558 555
 
559 556
 		$triple = $writer->drain(); // wbqc:xRANDOM ps:PID "value". or similar
560
-		return trim( str_replace( "$placeholder1:$placeholder2", '', $triple ) );
557
+		return trim(str_replace("$placeholder1:$placeholder2", '', $triple));
561 558
 	}
562 559
 
563 560
 	/**
564 561
 	 * Return SPARQL code for a string literal with $text as content.
565 562
 	 */
566
-	private function stringLiteral( string $text ): string {
567
-		return '"' . strtr( $text, [ '"' => '\\"', '\\' => '\\\\' ] ) . '"';
563
+	private function stringLiteral(string $text): string {
564
+		return '"'.strtr($text, ['"' => '\\"', '\\' => '\\\\']).'"';
568 565
 	}
569 566
 
570 567
 	/**
@@ -574,26 +571,26 @@  discard block
 block discarded – undo
574 571
 	 *
575 572
 	 * @return CachedEntityIds
576 573
 	 */
577
-	private function getOtherEntities( array $results ): CachedEntityIds {
574
+	private function getOtherEntities(array $results): CachedEntityIds {
578 575
 		$allResultBindings = [];
579 576
 		$metadatas = [];
580 577
 
581
-		foreach ( $results as $result ) {
578
+		foreach ($results as $result) {
582 579
 			$metadatas[] = $result->getMetadata();
583
-			$allResultBindings = array_merge( $allResultBindings, $result->getArray()['results']['bindings'] );
580
+			$allResultBindings = array_merge($allResultBindings, $result->getArray()['results']['bindings']);
584 581
 		}
585 582
 
586 583
 		$entityIds = array_map(
587
-			function ( $resultBindings ) {
584
+			function($resultBindings) {
588 585
 				$entityIRI = $resultBindings['otherEntity']['value'];
589
-				foreach ( $this->entityPrefixes as $entityPrefix ) {
590
-					$entityPrefixLength = strlen( $entityPrefix );
591
-					if ( substr( $entityIRI, 0, $entityPrefixLength ) === $entityPrefix ) {
586
+				foreach ($this->entityPrefixes as $entityPrefix) {
587
+					$entityPrefixLength = strlen($entityPrefix);
588
+					if (substr($entityIRI, 0, $entityPrefixLength) === $entityPrefix) {
592 589
 						try {
593 590
 							return $this->entityIdParser->parse(
594
-								substr( $entityIRI, $entityPrefixLength )
591
+								substr($entityIRI, $entityPrefixLength)
595 592
 							);
596
-						} catch ( EntityIdParsingException ) {
593
+						} catch (EntityIdParsingException) {
597 594
 							// fall through
598 595
 						}
599 596
 					}
@@ -607,8 +604,8 @@  discard block
 block discarded – undo
607 604
 		);
608 605
 
609 606
 		return new CachedEntityIds(
610
-			array_values( array_filter( array_unique( $entityIds ) ) ),
611
-			Metadata::merge( $metadatas )
607
+			array_values(array_filter(array_unique($entityIds))),
608
+			Metadata::merge($metadatas)
612 609
 		);
613 610
 	}
614 611
 
@@ -616,52 +613,52 @@  discard block
 block discarded – undo
616 613
 	 * @throws SparqlHelperException if the query times out or some other error occurs
617 614
 	 * @throws ConstraintParameterException if the $regex is invalid
618 615
 	 */
619
-	public function matchesRegularExpression( string $text, string $regex ): bool {
616
+	public function matchesRegularExpression(string $text, string $regex): bool {
620 617
 		// caching wrapper around matchesRegularExpressionWithSparql
621 618
 
622
-		$textHash = hash( 'sha256', $text );
619
+		$textHash = hash('sha256', $text);
623 620
 		$cacheKey = $this->cache->makeKey(
624 621
 			'WikibaseQualityConstraints', // extension
625 622
 			'regex', // action
626 623
 			'WDQS-Java', // regex flavor
627
-			hash( 'sha256', $regex )
624
+			hash('sha256', $regex)
628 625
 		);
629 626
 
630
-		$metric = $this->statsFactory->getCounter( 'regex_cache_total' );
627
+		$metric = $this->statsFactory->getCounter('regex_cache_total');
631 628
 
632 629
 		$cacheMapArray = $this->cache->getWithSetCallback(
633 630
 			$cacheKey,
634 631
 			WANObjectCache::TTL_DAY,
635
-			function ( $cacheMapArray ) use ( $text, $regex, $textHash, $metric ) {
632
+			function($cacheMapArray) use ($text, $regex, $textHash, $metric) {
636 633
 				// Initialize the cache map if not set
637
-				if ( $cacheMapArray === false ) {
634
+				if ($cacheMapArray === false) {
638 635
 					$metric
639
-						->setLabel( 'operation', 'refresh' )
640
-						->setLabel( 'status', 'init' )
636
+						->setLabel('operation', 'refresh')
637
+						->setLabel('status', 'init')
641 638
 						->increment();
642 639
 
643 640
 					return [];
644 641
 				}
645 642
 
646
-				$cacheMap = MapCacheLRU::newFromArray( $cacheMapArray, $this->cacheMapSize );
647
-				if ( $cacheMap->has( $textHash ) ) {
643
+				$cacheMap = MapCacheLRU::newFromArray($cacheMapArray, $this->cacheMapSize);
644
+				if ($cacheMap->has($textHash)) {
648 645
 					$metric
649
-						->setLabel( 'operation', 'refresh' )
650
-						->setLabel( 'status', 'hit' )
646
+						->setLabel('operation', 'refresh')
647
+						->setLabel('status', 'hit')
651 648
 						->increment();
652 649
 
653
-					$cacheMap->get( $textHash ); // ping cache
650
+					$cacheMap->get($textHash); // ping cache
654 651
 				} else {
655 652
 					$metric
656
-						->setLabel( 'operation', 'refresh' )
657
-						->setLabel( 'status', 'miss' )
653
+						->setLabel('operation', 'refresh')
654
+						->setLabel('status', 'miss')
658 655
 						->increment();
659 656
 
660 657
 					try {
661
-						$matches = $this->matchesRegularExpressionWithSparql( $text, $regex );
662
-					} catch ( ConstraintParameterException $e ) {
663
-						$matches = $this->serializeConstraintParameterException( $e );
664
-					} catch ( SparqlHelperException ) {
658
+						$matches = $this->matchesRegularExpressionWithSparql($text, $regex);
659
+					} catch (ConstraintParameterException $e) {
660
+						$matches = $this->serializeConstraintParameterException($e);
661
+					} catch (SparqlHelperException) {
665 662
 						// don’t cache this
666 663
 						return $cacheMap->toArray();
667 664
 					}
@@ -685,48 +682,48 @@  discard block
 block discarded – undo
685 682
 			]
686 683
 		);
687 684
 
688
-		if ( isset( $cacheMapArray[$textHash] ) ) {
685
+		if (isset($cacheMapArray[$textHash])) {
689 686
 			$metric
690
-				->setLabel( 'operation', 'none' )
691
-				->setLabel( 'status', 'hit' )
687
+				->setLabel('operation', 'none')
688
+				->setLabel('status', 'hit')
692 689
 				->increment();
693 690
 
694 691
 			$matches = $cacheMapArray[$textHash];
695
-			if ( is_bool( $matches ) ) {
692
+			if (is_bool($matches)) {
696 693
 				return $matches;
697
-			} elseif ( is_array( $matches ) &&
698
-				$matches['type'] == ConstraintParameterException::class ) {
699
-				throw $this->deserializeConstraintParameterException( $matches );
694
+			} elseif (is_array($matches) &&
695
+				$matches['type'] == ConstraintParameterException::class) {
696
+				throw $this->deserializeConstraintParameterException($matches);
700 697
 			} else {
701 698
 				throw new UnexpectedValueException(
702
-					'Value of unknown type in object cache (' .
703
-					'cache key: ' . $cacheKey . ', ' .
704
-					'cache map key: ' . $textHash . ', ' .
705
-					'value type: ' . get_debug_type( $matches ) . ')'
699
+					'Value of unknown type in object cache ('.
700
+					'cache key: '.$cacheKey.', '.
701
+					'cache map key: '.$textHash.', '.
702
+					'value type: '.get_debug_type($matches).')'
706 703
 				);
707 704
 			}
708 705
 		} else {
709 706
 			$metric
710
-				->setLabel( 'operation', 'none' )
711
-				->setLabel( 'status', 'miss' )
707
+				->setLabel('operation', 'none')
708
+				->setLabel('status', 'miss')
712 709
 				->increment();
713 710
 
714
-			return $this->matchesRegularExpressionWithSparql( $text, $regex );
711
+			return $this->matchesRegularExpressionWithSparql($text, $regex);
715 712
 		}
716 713
 	}
717 714
 
718
-	private function serializeConstraintParameterException( ConstraintParameterException $cpe ): array {
715
+	private function serializeConstraintParameterException(ConstraintParameterException $cpe): array {
719 716
 		return [
720 717
 			'type' => ConstraintParameterException::class,
721
-			'violationMessage' => $this->violationMessageSerializer->serialize( $cpe->getViolationMessage() ),
718
+			'violationMessage' => $this->violationMessageSerializer->serialize($cpe->getViolationMessage()),
722 719
 		];
723 720
 	}
724 721
 
725
-	private function deserializeConstraintParameterException( array $serialization ): ConstraintParameterException {
722
+	private function deserializeConstraintParameterException(array $serialization): ConstraintParameterException {
726 723
 		$message = $this->violationMessageDeserializer->deserialize(
727 724
 			$serialization['violationMessage']
728 725
 		);
729
-		return new ConstraintParameterException( $message );
726
+		return new ConstraintParameterException($message);
730 727
 	}
731 728
 
732 729
 	/**
@@ -736,25 +733,25 @@  discard block
 block discarded – undo
736 733
 	 * @throws SparqlHelperException if the query times out or some other error occurs
737 734
 	 * @throws ConstraintParameterException if the $regex is invalid
738 735
 	 */
739
-	public function matchesRegularExpressionWithSparql( string $text, string $regex ): bool {
740
-		$textStringLiteral = $this->stringLiteral( $text );
741
-		$regexStringLiteral = $this->stringLiteral( '^(?:' . $regex . ')$' );
736
+	public function matchesRegularExpressionWithSparql(string $text, string $regex): bool {
737
+		$textStringLiteral = $this->stringLiteral($text);
738
+		$regexStringLiteral = $this->stringLiteral('^(?:'.$regex.')$');
742 739
 
743 740
 		$query = <<<EOF
744 741
 SELECT (REGEX($textStringLiteral, $regexStringLiteral) AS ?matches) {}
745 742
 EOF;
746 743
 
747
-		$result = $this->runQuery( $query, $this->primaryEndpoint, false );
744
+		$result = $this->runQuery($query, $this->primaryEndpoint, false);
748 745
 
749 746
 		$vars = $result->getArray()['results']['bindings'][0];
750
-		if ( array_key_exists( 'matches', $vars ) ) {
747
+		if (array_key_exists('matches', $vars)) {
751 748
 			// true or false ⇒ regex okay, text matches or not
752 749
 			return $vars['matches']['value'] === 'true';
753 750
 		} else {
754 751
 			// empty result: regex broken
755 752
 			throw new ConstraintParameterException(
756
-				( new ViolationMessage( 'wbqc-violation-message-parameter-regex' ) )
757
-					->withInlineCode( $regex, Role::CONSTRAINT_PARAMETER_VALUE )
753
+				(new ViolationMessage('wbqc-violation-message-parameter-regex'))
754
+					->withInlineCode($regex, Role::CONSTRAINT_PARAMETER_VALUE)
758 755
 			);
759 756
 		}
760 757
 	}
@@ -762,14 +759,14 @@  discard block
 block discarded – undo
762 759
 	/**
763 760
 	 * Check whether the text content of an error response indicates a query timeout.
764 761
 	 */
765
-	public function isTimeout( string $responseContent ): bool {
766
-		$timeoutRegex = implode( '|', array_map(
767
-			static function ( $fqn ) {
768
-				return preg_quote( $fqn, '/' );
762
+	public function isTimeout(string $responseContent): bool {
763
+		$timeoutRegex = implode('|', array_map(
764
+			static function($fqn) {
765
+				return preg_quote($fqn, '/');
769 766
 			},
770 767
 			$this->timeoutExceptionClasses
771
-		) );
772
-		return (bool)preg_match( '/' . $timeoutRegex . '/', $responseContent );
768
+		));
769
+		return (bool) preg_match('/'.$timeoutRegex.'/', $responseContent);
773 770
 	}
774 771
 
775 772
 	/**
@@ -781,17 +778,17 @@  discard block
 block discarded – undo
781 778
 	 * @return int|bool the max-age (in seconds)
782 779
 	 * or a plain boolean if no max-age can be determined
783 780
 	 */
784
-	public function getCacheMaxAge( array $responseHeaders ) {
781
+	public function getCacheMaxAge(array $responseHeaders) {
785 782
 		if (
786
-			array_key_exists( 'x-cache-status', $responseHeaders ) &&
787
-			preg_match( '/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0] )
783
+			array_key_exists('x-cache-status', $responseHeaders) &&
784
+			preg_match('/^hit(?:-.*)?$/', $responseHeaders['x-cache-status'][0])
788 785
 		) {
789 786
 			$maxage = [];
790 787
 			if (
791
-				array_key_exists( 'cache-control', $responseHeaders ) &&
792
-				preg_match( '/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage )
788
+				array_key_exists('cache-control', $responseHeaders) &&
789
+				preg_match('/\bmax-age=(\d+)\b/', $responseHeaders['cache-control'][0], $maxage)
793 790
 			) {
794
-				return intval( $maxage[1] );
791
+				return intval($maxage[1]);
795 792
 			} else {
796 793
 				return true;
797 794
 			}
@@ -812,34 +809,34 @@  discard block
 block discarded – undo
812 809
 	 * or SparlHelper::EMPTY_RETRY_AFTER if there is an empty Retry-After
813 810
 	 * or SparlHelper::INVALID_RETRY_AFTER if there is something wrong with the format
814 811
 	 */
815
-	public function getThrottling( MWHttpRequest $request ) {
816
-		$retryAfterValue = $request->getResponseHeader( 'Retry-After' );
817
-		if ( $retryAfterValue === null ) {
812
+	public function getThrottling(MWHttpRequest $request) {
813
+		$retryAfterValue = $request->getResponseHeader('Retry-After');
814
+		if ($retryAfterValue === null) {
818 815
 			return self::NO_RETRY_AFTER;
819 816
 		}
820 817
 
821
-		$trimmedRetryAfterValue = trim( $retryAfterValue );
822
-		if ( $trimmedRetryAfterValue === '' ) {
818
+		$trimmedRetryAfterValue = trim($retryAfterValue);
819
+		if ($trimmedRetryAfterValue === '') {
823 820
 			return self::EMPTY_RETRY_AFTER;
824 821
 		}
825 822
 
826
-		if ( is_numeric( $trimmedRetryAfterValue ) ) {
827
-			$delaySeconds = (int)$trimmedRetryAfterValue;
828
-			if ( $delaySeconds >= 0 ) {
829
-				return $this->getTimestampInFuture( new DateInterval( 'PT' . $delaySeconds . 'S' ) );
823
+		if (is_numeric($trimmedRetryAfterValue)) {
824
+			$delaySeconds = (int) $trimmedRetryAfterValue;
825
+			if ($delaySeconds >= 0) {
826
+				return $this->getTimestampInFuture(new DateInterval('PT'.$delaySeconds.'S'));
830 827
 			}
831 828
 		} else {
832
-			$return = strtotime( $trimmedRetryAfterValue );
833
-			if ( $return !== false ) {
834
-				return new ConvertibleTimestamp( $return );
829
+			$return = strtotime($trimmedRetryAfterValue);
830
+			if ($return !== false) {
831
+				return new ConvertibleTimestamp($return);
835 832
 			}
836 833
 		}
837 834
 		return self::INVALID_RETRY_AFTER;
838 835
 	}
839 836
 
840
-	private function getTimestampInFuture( DateInterval $delta ): ConvertibleTimestamp {
837
+	private function getTimestampInFuture(DateInterval $delta): ConvertibleTimestamp {
841 838
 		$now = new ConvertibleTimestamp();
842
-		return new ConvertibleTimestamp( $now->timestamp->add( $delta ) );
839
+		return new ConvertibleTimestamp($now->timestamp->add($delta));
843 840
 	}
844 841
 
845 842
 	/**
@@ -854,92 +851,91 @@  discard block
 block discarded – undo
854 851
 	 *
855 852
 	 * @throws SparqlHelperException if the query times out or some other error occurs
856 853
 	 */
857
-	protected function runQuery( string $query, string $endpoint, bool $needsPrefixes = true ): CachedQueryResults {
858
-		if ( $this->throttlingLock->isLocked( self::EXPIRY_LOCK_ID ) ) {
854
+	protected function runQuery(string $query, string $endpoint, bool $needsPrefixes = true): CachedQueryResults {
855
+		if ($this->throttlingLock->isLocked(self::EXPIRY_LOCK_ID)) {
859 856
 			$this->statsFactory
860
-				->getCounter( 'sparql_throttling_total' )
857
+				->getCounter('sparql_throttling_total')
861 858
 				->increment();
862 859
 
863 860
 			throw new TooManySparqlRequestsException();
864 861
 		}
865 862
 
866
-		if ( $this->sparqlHasWikibaseSupport ) {
863
+		if ($this->sparqlHasWikibaseSupport) {
867 864
 			$needsPrefixes = false;
868 865
 		}
869 866
 
870
-		if ( $needsPrefixes ) {
871
-			$query = $this->prefixes . $query;
867
+		if ($needsPrefixes) {
868
+			$query = $this->prefixes.$query;
872 869
 		}
873
-		$query = "#wbqc\n" . $query;
870
+		$query = "#wbqc\n".$query;
874 871
 
875
-		$url = $endpoint . '?' . http_build_query(
872
+		$url = $endpoint.'?'.http_build_query(
876 873
 			[
877 874
 				'query' => $query,
878 875
 				'format' => 'json',
879 876
 				'maxQueryTimeMillis' => $this->maxQueryTimeMillis,
880 877
 			],
881
-			'', ini_get( 'arg_separator.output' ),
878
+			'', ini_get('arg_separator.output'),
882 879
 			// encode spaces with %20, not +
883 880
 			PHP_QUERY_RFC3986
884 881
 		);
885 882
 
886 883
 		$options = [
887 884
 			'method' => 'GET',
888
-			'timeout' => (int)round( ( $this->maxQueryTimeMillis + 1000 ) / 1000 ),
885
+			'timeout' => (int) round(($this->maxQueryTimeMillis + 1000) / 1000),
889 886
 			'connectTimeout' => 'default',
890 887
 			'userAgent' => $this->defaultUserAgent,
891 888
 		];
892
-		$request = $this->requestFactory->create( $url, $options, __METHOD__ );
889
+		$request = $this->requestFactory->create($url, $options, __METHOD__);
893 890
 
894 891
 		$timing = $this->statsFactory
895
-			->getTiming( 'sparql_runQuery_duration_seconds' );
892
+			->getTiming('sparql_runQuery_duration_seconds');
896 893
 
897 894
 		$timing->start();
898 895
 		$requestStatus = $request->execute();
899 896
 		$timing->stop();
900 897
 
901
-		$this->guardAgainstTooManyRequestsError( $request );
898
+		$this->guardAgainstTooManyRequestsError($request);
902 899
 
903
-		$maxAge = $this->getCacheMaxAge( $request->getResponseHeaders() );
904
-		if ( $maxAge ) {
905
-			$this->statsFactory->getCounter( 'sparql_cached_total' )
900
+		$maxAge = $this->getCacheMaxAge($request->getResponseHeaders());
901
+		if ($maxAge) {
902
+			$this->statsFactory->getCounter('sparql_cached_total')
906 903
 				->increment();
907 904
 		}
908 905
 
909
-		$metric = $this->statsFactory->getCounter( 'sparql_error_total' );
910
-		if ( $requestStatus->isOK() ) {
906
+		$metric = $this->statsFactory->getCounter('sparql_error_total');
907
+		if ($requestStatus->isOK()) {
911 908
 			$json = $request->getContent();
912
-			$jsonStatus = FormatJson::parse( $json, FormatJson::FORCE_ASSOC );
909
+			$jsonStatus = FormatJson::parse($json, FormatJson::FORCE_ASSOC);
913 910
 			'@phan-var \MediaWiki\Status\Status<array> $jsonStatus';
914
-			if ( $jsonStatus->isOK() ) {
911
+			if ($jsonStatus->isOK()) {
915 912
 				return new CachedQueryResults(
916 913
 					$jsonStatus->getValue(),
917 914
 					Metadata::ofCachingMetadata(
918 915
 						$maxAge ?
919
-							CachingMetadata::ofMaximumAgeInSeconds( $maxAge ) :
920
-							CachingMetadata::fresh()
916
+							CachingMetadata::ofMaximumAgeInSeconds($maxAge) : CachingMetadata::fresh()
921 917
 					)
922 918
 				);
923 919
 			} else {
924 920
 				$jsonErrorCode = $jsonStatus->getErrors()[0]['message'];
925 921
 				$metric
926
-					->setLabel( 'type', 'json' )
927
-					->setLabel( 'code', "$jsonErrorCode" )
922
+					->setLabel('type', 'json')
923
+					->setLabel('code', "$jsonErrorCode")
928 924
 					->increment();
929 925
 				// fall through to general error handling
930 926
 			}
931 927
 		} else {
932 928
 			$metric
933
-				->setLabel( 'type', 'http' )
934
-				->setLabel( 'code', "{$request->getStatus()}" )
929
+				->setLabel('type', 'http')
930
+				->setLabel('code', "{$request->getStatus()}")
935 931
 				->increment();
936 932
 			// fall through to general error handling
937 933
 		}
938 934
 
939
-		if ( $this->isTimeout( $request->getContent() ) ) {
935
+		if ($this->isTimeout($request->getContent())) {
940 936
 			$metric
941
-				->setLabel( 'type', 'timeout' )
942
-				->setLabel( 'code', 'none' )
937
+				->setLabel('type', 'timeout')
938
+				->setLabel('code', 'none')
943 939
 				->increment();
944 940
 		}
945 941
 
@@ -952,31 +948,31 @@  discard block
 block discarded – undo
952 948
 	 * @param MWHttpRequest $request
953 949
 	 * @throws TooManySparqlRequestsException
954 950
 	 */
955
-	private function guardAgainstTooManyRequestsError( MWHttpRequest $request ): void {
956
-		if ( $request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS ) {
951
+	private function guardAgainstTooManyRequestsError(MWHttpRequest $request): void {
952
+		if ($request->getStatus() !== self::HTTP_TOO_MANY_REQUESTS) {
957 953
 			return;
958 954
 		}
959 955
 
960 956
 		$fallbackBlockDuration = $this->sparqlThrottlingFallbackDuration;
961 957
 
962
-		if ( $fallbackBlockDuration < 0 ) {
963
-			throw new InvalidArgumentException( 'Fallback duration must be positive int but is: ' .
964
-				$fallbackBlockDuration );
958
+		if ($fallbackBlockDuration < 0) {
959
+			throw new InvalidArgumentException('Fallback duration must be positive int but is: '.
960
+				$fallbackBlockDuration);
965 961
 		}
966 962
 
967
-		$this->statsFactory->getCounter( 'sparql_throttling_total' )
963
+		$this->statsFactory->getCounter('sparql_throttling_total')
968 964
 			->increment();
969 965
 
970
-		$throttlingUntil = $this->getThrottling( $request );
971
-		if ( !( $throttlingUntil instanceof ConvertibleTimestamp ) ) {
972
-			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid( $request );
966
+		$throttlingUntil = $this->getThrottling($request);
967
+		if (!($throttlingUntil instanceof ConvertibleTimestamp)) {
968
+			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterInvalid($request);
973 969
 			$this->throttlingLock->lock(
974 970
 				self::EXPIRY_LOCK_ID,
975
-				$this->getTimestampInFuture( new DateInterval( 'PT' . $fallbackBlockDuration . 'S' ) )
971
+				$this->getTimestampInFuture(new DateInterval('PT'.$fallbackBlockDuration.'S'))
976 972
 			);
977 973
 		} else {
978
-			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent( $throttlingUntil, $request );
979
-			$this->throttlingLock->lock( self::EXPIRY_LOCK_ID, $throttlingUntil );
974
+			$this->loggingHelper->logSparqlHelperTooManyRequestsRetryAfterPresent($throttlingUntil, $request);
975
+			$this->throttlingLock->lock(self::EXPIRY_LOCK_ID, $throttlingUntil);
980 976
 		}
981 977
 		throw new TooManySparqlRequestsException();
982 978
 	}
Please login to merge, or discard this patch.
src/Specials/SpecialConstraintReport.php 1 patch
Spacing   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-declare( strict_types = 1 );
3
+declare(strict_types=1);
4 4
 
5 5
 namespace WikibaseQuality\ConstraintReport\Specials;
6 6
 
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 		Config $config,
92 92
 		StatsFactory $statsFactory
93 93
 	) {
94
-		parent::__construct( 'ConstraintReport', 'wbqc-check-constraints-uncached' );
94
+		parent::__construct('ConstraintReport', 'wbqc-check-constraints-uncached');
95 95
 
96 96
 		$this->entityLookup = $entityLookup;
97 97
 		$this->entityTitleLookup = $entityTitleLookup;
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 
112 112
 		$this->violationMessageRenderer = $violationMessageRendererFactory->getViolationMessageRenderer(
113 113
 			$language,
114
-			$languageFallbackChainFactory->newFromLanguage( $language ),
114
+			$languageFallbackChainFactory->newFromLanguage($language),
115 115
 			$this->getContext()
116 116
 		);
117 117
 
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 	 * @inheritDoc
146 146
 	 */
147 147
 	public function getDescription() {
148
-		return $this->msg( 'wbqc-constraintreport' );
148
+		return $this->msg('wbqc-constraintreport');
149 149
 	}
150 150
 
151 151
 	/**
@@ -157,73 +157,73 @@  discard block
 block discarded – undo
157 157
 	 * @throws EntityIdParsingException
158 158
 	 * @throws UnexpectedValueException
159 159
 	 */
160
-	public function execute( $subPage ) {
161
-		parent::execute( $subPage );
160
+	public function execute($subPage) {
161
+		parent::execute($subPage);
162 162
 
163 163
 		$out = $this->getOutput();
164 164
 
165
-		$postRequest = $this->getContext()->getRequest()->getVal( 'entityid' );
166
-		if ( $postRequest ) {
165
+		$postRequest = $this->getContext()->getRequest()->getVal('entityid');
166
+		if ($postRequest) {
167 167
 			try {
168
-				$entityId = $this->entityIdParser->parse( $postRequest );
169
-				$out->redirect( $this->getPageTitle( $entityId->getSerialization() )->getLocalURL() );
168
+				$entityId = $this->entityIdParser->parse($postRequest);
169
+				$out->redirect($this->getPageTitle($entityId->getSerialization())->getLocalURL());
170 170
 				return;
171
-			} catch ( EntityIdParsingException ) {
171
+			} catch (EntityIdParsingException) {
172 172
 				// fall through, error is shown later
173 173
 			}
174 174
 		}
175 175
 
176 176
 		$out->enableOOUI();
177
-		$out->addModules( $this->getModules() );
177
+		$out->addModules($this->getModules());
178 178
 
179 179
 		$this->setHeaders();
180 180
 
181
-		$out->addHTML( $this->getExplanationText() );
181
+		$out->addHTML($this->getExplanationText());
182 182
 		$this->buildEntityIdForm();
183 183
 
184
-		if ( $postRequest ) {
184
+		if ($postRequest) {
185 185
 			// must be an invalid entity ID (otherwise we would have redirected and returned above)
186 186
 			$out->addHTML(
187
-				$this->buildNotice( 'wbqc-constraintreport-invalid-entity-id', true )
187
+				$this->buildNotice('wbqc-constraintreport-invalid-entity-id', true)
188 188
 			);
189 189
 			return;
190 190
 		}
191 191
 
192
-		if ( !$subPage ) {
192
+		if (!$subPage) {
193 193
 			return;
194 194
 		}
195 195
 
196 196
 		try {
197
-			$entityId = $this->entityIdParser->parse( $subPage );
198
-		} catch ( EntityIdParsingException ) {
197
+			$entityId = $this->entityIdParser->parse($subPage);
198
+		} catch (EntityIdParsingException) {
199 199
 			$out->addHTML(
200
-				$this->buildNotice( 'wbqc-constraintreport-invalid-entity-id', true )
200
+				$this->buildNotice('wbqc-constraintreport-invalid-entity-id', true)
201 201
 			);
202 202
 			return;
203 203
 		}
204 204
 
205
-		if ( !$this->entityLookup->hasEntity( $entityId ) ) {
205
+		if (!$this->entityLookup->hasEntity($entityId)) {
206 206
 			$out->addHTML(
207
-				$this->buildNotice( 'wbqc-constraintreport-not-existent-entity', true )
207
+				$this->buildNotice('wbqc-constraintreport-not-existent-entity', true)
208 208
 			);
209 209
 			return;
210 210
 		}
211 211
 
212
-		$this->statsFactory->getCounter( 'special_constraint_report_execute_check_total' )
212
+		$this->statsFactory->getCounter('special_constraint_report_execute_check_total')
213 213
 			->increment();
214
-		$results = $this->constraintChecker->checkAgainstConstraintsOnEntityId( $entityId );
214
+		$results = $this->constraintChecker->checkAgainstConstraintsOnEntityId($entityId);
215 215
 
216
-		if ( !$results ) {
217
-			$out->addHTML( $this->buildResultHeader( $entityId ) .
218
-				$this->buildNotice( 'wbqc-constraintreport-empty-result' )
216
+		if (!$results) {
217
+			$out->addHTML($this->buildResultHeader($entityId).
218
+				$this->buildNotice('wbqc-constraintreport-empty-result')
219 219
 			);
220 220
 			return;
221 221
 		}
222 222
 
223 223
 		$out->addHTML(
224
-			$this->buildResultHeader( $entityId )
225
-			. $this->buildSummary( $results )
226
-			. $this->buildResultTable( $entityId, $results )
224
+			$this->buildResultHeader($entityId)
225
+			. $this->buildSummary($results)
226
+			. $this->buildResultTable($entityId, $results)
227 227
 		);
228 228
 	}
229 229
 
@@ -238,15 +238,15 @@  discard block
 block discarded – undo
238 238
 				'name' => 'entityid',
239 239
 				'label-message' => 'wbqc-constraintreport-form-entityid-label',
240 240
 				'cssclass' => 'wbqc-constraintreport-form-entity-id',
241
-				'placeholder' => $this->msg( 'wbqc-constraintreport-form-entityid-placeholder' )->text(),
241
+				'placeholder' => $this->msg('wbqc-constraintreport-form-entityid-placeholder')->text(),
242 242
 				'required' => true,
243 243
 			],
244 244
 		];
245
-		$htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext(),
245
+		$htmlForm = HTMLForm::factory('ooui', $formDescriptor, $this->getContext(),
246 246
 			'wbqc-constraintreport-form'
247 247
 		);
248
-		$htmlForm->setSubmitText( $this->msg( 'wbqc-constraintreport-form-submit-label' )->text() );
249
-		$htmlForm->setSubmitCallback( static fn () => false );
248
+		$htmlForm->setSubmitText($this->msg('wbqc-constraintreport-form-submit-label')->text());
249
+		$htmlForm->setSubmitCallback(static fn () => false);
250 250
 		$htmlForm->show();
251 251
 	}
252 252
 
@@ -260,16 +260,16 @@  discard block
 block discarded – undo
260 260
 	 *
261 261
 	 * @return string HTML
262 262
 	 */
263
-	private function buildNotice( string $messageKey, bool $error = false ): string {
264
-		$cssClasses = [ 'wbqc-constraintreport-notice' ];
265
-		if ( $error ) {
263
+	private function buildNotice(string $messageKey, bool $error = false): string {
264
+		$cssClasses = ['wbqc-constraintreport-notice'];
265
+		if ($error) {
266 266
 			$cssClasses[] = ' wbqc-constraintreport-notice-error';
267 267
 		}
268 268
 
269 269
 		return Html::element(
270 270
 			'p',
271
-			[ 'class' => $cssClasses ],
272
-			$this->msg( $messageKey )->text()
271
+			['class' => $cssClasses],
272
+			$this->msg($messageKey)->text()
273 273
 		);
274 274
 	}
275 275
 
@@ -279,16 +279,16 @@  discard block
 block discarded – undo
279 279
 	private function getExplanationText(): string {
280 280
 		return Html::rawElement(
281 281
 			'div',
282
-			[ 'class' => 'wbqc-explanation' ],
282
+			['class' => 'wbqc-explanation'],
283 283
 			Html::element(
284 284
 				'p',
285 285
 				[],
286
-				$this->msg( 'wbqc-constraintreport-explanation-part-one' )->text()
286
+				$this->msg('wbqc-constraintreport-explanation-part-one')->text()
287 287
 			)
288 288
 			. Html::element(
289 289
 				'p',
290 290
 				[],
291
-				$this->msg( 'wbqc-constraintreport-explanation-part-two' )->text()
291
+				$this->msg('wbqc-constraintreport-explanation-part-two')->text()
292 292
 			)
293 293
 		);
294 294
 	}
@@ -299,31 +299,31 @@  discard block
 block discarded – undo
299 299
 	 *
300 300
 	 * @return string HTML
301 301
 	 */
302
-	private function buildResultTable( EntityId $entityId, array $results ): string {
302
+	private function buildResultTable(EntityId $entityId, array $results): string {
303 303
 		// Set table headers
304 304
 		$table = new HtmlTableBuilder(
305 305
 			[
306 306
 				new HtmlTableHeaderBuilder(
307
-					$this->msg( 'wbqc-constraintreport-result-table-header-status' )->text(),
307
+					$this->msg('wbqc-constraintreport-result-table-header-status')->text(),
308 308
 					true
309 309
 				),
310 310
 				new HtmlTableHeaderBuilder(
311
-					$this->msg( 'wbqc-constraintreport-result-table-header-property' )->text(),
311
+					$this->msg('wbqc-constraintreport-result-table-header-property')->text(),
312 312
 					true
313 313
 				),
314 314
 				new HtmlTableHeaderBuilder(
315
-					$this->msg( 'wbqc-constraintreport-result-table-header-message' )->text(),
315
+					$this->msg('wbqc-constraintreport-result-table-header-message')->text(),
316 316
 					true
317 317
 				),
318 318
 				new HtmlTableHeaderBuilder(
319
-					$this->msg( 'wbqc-constraintreport-result-table-header-constraint' )->text(),
319
+					$this->msg('wbqc-constraintreport-result-table-header-constraint')->text(),
320 320
 					true
321 321
 				),
322 322
 			]
323 323
 		);
324 324
 
325
-		foreach ( $results as $result ) {
326
-			$this->appendToResultTable( $table, $entityId, $result );
325
+		foreach ($results as $result) {
326
+			$this->appendToResultTable($table, $entityId, $result);
327 327
 		}
328 328
 
329 329
 		return $table->toHtml();
@@ -335,35 +335,35 @@  discard block
 block discarded – undo
335 335
 		CheckResult $result
336 336
 	): void {
337 337
 		$message = $result->getMessage();
338
-		if ( !$message ) {
338
+		if (!$message) {
339 339
 			// no row for this result
340 340
 			return;
341 341
 		}
342 342
 
343 343
 		// Status column
344
-		$statusColumn = $this->formatStatus( $result->getStatus() );
344
+		$statusColumn = $this->formatStatus($result->getStatus());
345 345
 
346 346
 		// Property column
347
-		$propertyId = new NumericPropertyId( $result->getContextCursor()->getSnakPropertyId() );
347
+		$propertyId = new NumericPropertyId($result->getContextCursor()->getSnakPropertyId());
348 348
 		$propertyColumn = $this->getClaimLink(
349 349
 			$entityId,
350 350
 			$propertyId,
351
-			$this->entityIdLabelFormatter->formatEntityId( $propertyId )
351
+			$this->entityIdLabelFormatter->formatEntityId($propertyId)
352 352
 		);
353 353
 
354 354
 		// Message column
355
-		$messageColumn = $this->violationMessageRenderer->render( $message );
355
+		$messageColumn = $this->violationMessageRenderer->render($message);
356 356
 
357 357
 		// Constraint column
358 358
 		$constraintTypeItemId = $result->getConstraint()->getConstraintTypeItemId();
359 359
 		try {
360
-			$constraintTypeLabel = $this->entityIdLabelFormatter->formatEntityId( new ItemId( $constraintTypeItemId ) );
361
-		} catch ( InvalidArgumentException ) {
362
-			$constraintTypeLabel = htmlspecialchars( $constraintTypeItemId );
360
+			$constraintTypeLabel = $this->entityIdLabelFormatter->formatEntityId(new ItemId($constraintTypeItemId));
361
+		} catch (InvalidArgumentException) {
362
+			$constraintTypeLabel = htmlspecialchars($constraintTypeItemId);
363 363
 		}
364 364
 		$constraintColumn = $this->getClaimLink(
365 365
 			$propertyId,
366
-			new NumericPropertyId( $this->config->get( 'WBQualityConstraintsPropertyConstraintId' ) ),
366
+			new NumericPropertyId($this->config->get('WBQualityConstraintsPropertyConstraintId')),
367 367
 			$constraintTypeLabel
368 368
 		);
369 369
 
@@ -371,16 +371,16 @@  discard block
 block discarded – undo
371 371
 		$table->appendRow(
372 372
 			[
373 373
 				new HtmlTableCellBuilder(
374
-					new HtmlArmor( $statusColumn )
374
+					new HtmlArmor($statusColumn)
375 375
 				),
376 376
 				new HtmlTableCellBuilder(
377
-					new HtmlArmor( $propertyColumn )
377
+					new HtmlArmor($propertyColumn)
378 378
 				),
379 379
 				new HtmlTableCellBuilder(
380
-					new HtmlArmor( $messageColumn )
380
+					new HtmlArmor($messageColumn)
381 381
 				),
382 382
 				new HtmlTableCellBuilder(
383
-					new HtmlArmor( $constraintColumn )
383
+					new HtmlArmor($constraintColumn)
384 384
 				),
385 385
 			]
386 386
 		);
@@ -393,15 +393,15 @@  discard block
 block discarded – undo
393 393
 	 *
394 394
 	 * @return string HTML
395 395
 	 */
396
-	protected function buildResultHeader( EntityId $entityId ): string {
396
+	protected function buildResultHeader(EntityId $entityId): string {
397 397
 		return Html::rawElement(
398 398
 			'h3',
399 399
 			[],
400
-			$this->msg( 'wbqc-constraintreport-result-headline' )->escaped() .
401
-				$this->msg( 'word-separator' )->escaped() .
402
-				$this->entityIdLinkFormatter->formatEntityId( $entityId ) .
403
-				$this->msg( 'word-separator' )->escaped() .
404
-				$this->msg( 'parentheses', $entityId->getSerialization() )->escaped()
400
+			$this->msg('wbqc-constraintreport-result-headline')->escaped().
401
+				$this->msg('word-separator')->escaped().
402
+				$this->entityIdLinkFormatter->formatEntityId($entityId).
403
+				$this->msg('word-separator')->escaped().
404
+				$this->msg('parentheses', $entityId->getSerialization())->escaped()
405 405
 		);
406 406
 	}
407 407
 
@@ -412,23 +412,23 @@  discard block
 block discarded – undo
412 412
 	 *
413 413
 	 * @return string HTML
414 414
 	 */
415
-	protected function buildSummary( array $results ): string {
415
+	protected function buildSummary(array $results): string {
416 416
 		$statuses = [];
417
-		foreach ( $results as $result ) {
418
-			$status = strtolower( $result->getStatus() );
417
+		foreach ($results as $result) {
418
+			$status = strtolower($result->getStatus());
419 419
 			$statuses[$status] ??= 0;
420 420
 			$statuses[$status]++;
421 421
 		}
422 422
 
423 423
 		$statusElements = [];
424
-		foreach ( $statuses as $status => $count ) {
425
-			$statusElements[] = $this->formatStatus( $status ) .
426
-				$this->msg( 'colon-separator' )->escaped() .
427
-				htmlspecialchars( $this->getLanguage()->formatNum( $count ) );
424
+		foreach ($statuses as $status => $count) {
425
+			$statusElements[] = $this->formatStatus($status).
426
+				$this->msg('colon-separator')->escaped().
427
+				htmlspecialchars($this->getLanguage()->formatNum($count));
428 428
 		}
429 429
 
430
-		return Html::rawElement( 'p', [],
431
-			implode( $this->msg( 'comma-separator' )->escaped(), $statusElements )
430
+		return Html::rawElement('p', [],
431
+			implode($this->msg('comma-separator')->escaped(), $statusElements)
432 432
 		);
433 433
 	}
434 434
 
@@ -441,8 +441,8 @@  discard block
 block discarded – undo
441 441
 	 *
442 442
 	 * @return string HTML
443 443
 	 */
444
-	private function formatStatus( string $status ): string {
445
-		$messageName = "wbqc-constraintreport-status-" . strtolower( $status );
444
+	private function formatStatus(string $status): string {
445
+		$messageName = "wbqc-constraintreport-status-".strtolower($status);
446 446
 		$statusIcons = [
447 447
 			CheckResult::STATUS_SUGGESTION => [
448 448
 				'icon' => 'suggestion-constraint-violation',
@@ -459,21 +459,21 @@  discard block
 block discarded – undo
459 459
 			],
460 460
 		];
461 461
 
462
-		if ( array_key_exists( $status, $statusIcons ) ) {
463
-			$iconHtml = new IconWidget( $statusIcons[$status] ) .
464
-				$this->msg( 'word-separator' )->escaped();
462
+		if (array_key_exists($status, $statusIcons)) {
463
+			$iconHtml = new IconWidget($statusIcons[$status]).
464
+				$this->msg('word-separator')->escaped();
465 465
 		} else {
466 466
 			$iconHtml = '';
467 467
 		}
468 468
 
469
-		$labelWidget = new LabelWidget( [ 'label' => $this->msg( $messageName )->text() ] );
469
+		$labelWidget = new LabelWidget(['label' => $this->msg($messageName)->text()]);
470 470
 
471 471
 		return Html::rawElement(
472 472
 			'span',
473 473
 			[
474
-				'class' => 'wbqc-status wbqc-status-' . $status,
474
+				'class' => 'wbqc-status wbqc-status-'.$status,
475 475
 			],
476
-			$iconHtml . $labelWidget
476
+			$iconHtml.$labelWidget
477 477
 		);
478 478
 	}
479 479
 
@@ -491,10 +491,10 @@  discard block
 block discarded – undo
491 491
 		NumericPropertyId $propertyId,
492 492
 		string $text
493 493
 	): string {
494
-		$title = clone $this->entityTitleLookup->getTitleForId( $entityId );
495
-		$title->setFragment( $propertyId->getSerialization() );
494
+		$title = clone $this->entityTitleLookup->getTitleForId($entityId);
495
+		$title->setFragment($propertyId->getSerialization());
496 496
 
497
-		return Html::rawElement( 'a',
497
+		return Html::rawElement('a',
498 498
 			[
499 499
 				'href' => $title->getLinkURL(),
500 500
 				'target' => '_blank',
Please login to merge, or discard this patch.