Debian Codegraph @

includes/libs/StatusValue.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use Wikimedia\Assert\Assert;
22 use Wikimedia\Message\MessageParam;
23 use Wikimedia\Message\MessageSpecifier;
24 use Wikimedia\Message\MessageValue;
25
26 /**
27 * Generic operation result class
28 * Has warning/error list, boolean status and arbitrary value
29 *
30 * "Good" means the operation was completed with no warnings or errors.
31 *
32 * "OK" means the operation was partially or wholly completed.
33 *
34 * An operation which is not OK should have errors so that the user can be
35 * informed as to what went wrong. Calling the fatal() function sets an error
36 * message and simultaneously switches off the OK flag.
37 *
38 * The recommended pattern for functions returning StatusValue objects is
39 * to return a StatusValue unconditionally, both on success and on failure
40 * (similarly to Option, Maybe, Promise etc. objects in other languages) --
41 * so that the developer of the calling code is reminded that the function
42 * can fail, and so that a lack of error-handling will be explicit.
43 *
44 * This class accepts any MessageSpecifier objects. The use of Message objects
45 * should be avoided when serializability is needed. Use MessageValue in that
46 * case instead.
47 *
48 * @newable
49 * @stable to extend
50 * @since 1.25
51 */
52 class StatusValue implements Stringable {
53
54 /**
55 * @var bool
56 * @internal Only for use by Status. Use {@link self::isOK()} or {@link self::setOK()}.
57 */
58 protected $ok = true;
59
60 /**
61 * @var array[]
62 * @internal Only for use by Status. Use {@link self::getErrors()} (get full list),
63 * {@link self::splitByErrorType()} (get errors/warnings), or
64 * {@link self::fatal()}, {@link self::error()} or {@link self::warning()} (add error/warning).
65 */
66 protected $errors = [];
67
68 /** @var mixed */
69 public $value;
70
71 /** @var bool[] Map of (key => bool) to indicate success of each part of batch operations */
72 public $success = [];
73
74 /** @var int Counter for batch operations */
75 public $successCount = 0;
76
77 /** @var int Counter for batch operations */
78 public $failCount = 0;
79
80 /** @var mixed arbitrary extra data about the operation */
81 public $statusData;
82
83 /**
84 * Factory function for fatal errors
85 *
86 * @param string|MessageSpecifier $message Message key or object
87 * @param mixed ...$parameters
88 * @return static
89 */
90 public static function newFatal( $message, ...$parameters ) {
91 $result = new static();
92 $result->fatal( $message, ...$parameters );
93 return $result;
94 }
95
96 /**
97 * Factory function for good results
98 *
99 * @param mixed|null $value
100 * @return static
101 */
102 public static function newGood( $value = null ) {
103 $result = new static();
104 $result->value = $value;
105 return $result;
106 }
107
108 /**
109 * Splits this StatusValue object into two new StatusValue objects, one which contains only
110 * the error messages, and one that contains the warnings, only. The returned array is
111 * defined as:
112 * [
113 * 0 => object(StatusValue) # the StatusValue with error messages, only
114 * 1 => object(StatusValue) # The StatusValue with warning messages, only
115 * ]
116 *
117 * @return static[]
118 */
119 public function splitByErrorType() {
120 $errorsOnlyStatusValue = static::newGood();
121 $warningsOnlyStatusValue = static::newGood();
122 $warningsOnlyStatusValue->setResult( true, $this->getValue() );
123 $errorsOnlyStatusValue->setResult( $this->isOK(), $this->getValue() );
124
125 foreach ( $this->errors as $item ) {
126 if ( $item['type'] === 'warning' ) {
127 $warningsOnlyStatusValue->errors[] = $item;
128 } else {
129 $errorsOnlyStatusValue->errors[] = $item;
130 }
131 }
132
133 return [ $errorsOnlyStatusValue, $warningsOnlyStatusValue ];
134 }
135
136 /**
137 * Returns whether the operation completed and didn't have any error or
138 * warnings
139 *
140 * @return bool
141 */
142 public function isGood() {
143 return $this->ok && !$this->errors;
144 }
145
146 /**
147 * Returns whether the operation completed
148 *
149 * @return bool
150 */
151 public function isOK() {
152 return $this->ok;
153 }
154
155 /**
156 * @return mixed
157 */
158 public function getValue() {
159 return $this->value;
160 }
161
162 /**
163 * Get the list of errors
164 *
165 * Each error is a (message:string or MessageSpecifier,params:array) map
166 *
167 * @deprecated since 1.43 Use `->getMessages()` instead
168 * @return array[]
169 * @phan-return array{type:'warning'|'error', message:string|MessageSpecifier, params:array}[]
170 */
171 public function getErrors() {
172 return $this->errors;
173 }
174
175 /**
176 * Change operation status
177 *
178 * @param bool $ok
179 * @return $this
180 */
181 public function setOK( $ok ) {
182 $this->ok = $ok;
183 return $this;
184 }
185
186 /**
187 * Change operation result
188 *
189 * @param bool $ok Whether the operation completed
190 * @param mixed|null $value
191 * @return $this
192 */
193 public function setResult( $ok, $value = null ) {
194 $this->ok = (bool)$ok;
195 $this->value = $value;
196 return $this;
197 }
198
199 /**
200 * Add a new error to the error array ($this->errors) if that error is not already in the
201 * error array. Each error is passed as an array with the following fields:
202 *
203 * - type: 'error' or 'warning'
204 * - message: a string (message key) or MessageSpecifier
205 * - params: an array of string parameters
206 *
207 * If the new error is of type 'error' and it matches an existing error of type 'warning',
208 * the existing error is upgraded to type 'error'. An error provided as a MessageSpecifier
209 * will successfully match an error provided as the same string message key and array of
210 * parameters as separate array elements.
211 *
212 * @param array $newError
213 * @phan-param array{type:'warning'|'error', message:string|MessageSpecifier, params:array} $newError
214 * @return $this
215 */
216 private function addError( array $newError ) {
217 [ 'type' => $newType, 'message' => $newKey, 'params' => $newParams ] = $newError;
218 if ( $newKey instanceof MessageSpecifier ) {
219 if ( $newParams ) {
220 // Deprecate code like `Status::newFatal( wfMessage( 'foo' ), 'param' )`
221 // - the parameters have always been ignored, so this is usually a mistake.
222 wfDeprecatedMsg( 'Combining MessageSpecifier and parameters array' .
223 ' was deprecated in MediaWiki 1.43', '1.43' );
224 }
225 $newParams = $newKey->getParams();
226 $newKey = $newKey->getKey();
227 }
228
229 foreach ( $this->errors as [ 'type' => &$type, 'message' => $key, 'params' => $params ] ) {
230 if ( $key instanceof MessageSpecifier ) {
231 $params = $key->getParams();
232 $key = $key->getKey();
233 }
234
235 // This uses loose equality as we must support equality between MessageParam objects
236 // (e.g. ScalarParam), including when they are created separate and not by-ref equal.
237 if ( $newKey === $key && $newParams == $params ) {
238 if ( $type === 'warning' && $newType === 'error' ) {
239 $type = 'error';
240 }
241 return $this;
242 }
243 }
244
245 $this->errors[] = $newError;
246
247 return $this;
248 }
249
250 /**
251 * Add a new warning
252 *
253 * @param string|MessageSpecifier $message Message key or object
254 * @param mixed ...$parameters
255 * @return $this
256 */
257 public function warning( $message, ...$parameters ) {
258 return $this->addError( [
259 'type' => 'warning',
260 'message' => $message,
261 'params' => $parameters
262 ] );
263 }
264
265 /**
266 * Add an error, do not set fatal flag
267 * This can be used for non-fatal errors
268 *
269 * @param string|MessageSpecifier $message Message key or object
270 * @param mixed ...$parameters
271 * @return $this
272 */
273 public function error( $message, ...$parameters ) {
274 return $this->addError( [
275 'type' => 'error',
276 'message' => $message,
277 'params' => $parameters
278 ] );
279 }
280
281 /**
282 * Add an error and set OK to false, indicating that the operation
283 * as a whole was fatal
284 *
285 * @param string|MessageSpecifier $message Message key or object
286 * @param mixed ...$parameters
287 * @return $this
288 */
289 public function fatal( $message, ...$parameters ) {
290 $this->ok = false;
291 return $this->error( $message, ...$parameters );
292 }
293
294 /**
295 * Merge another status object into this one
296 *
297 * @param StatusValue $other
298 * @param bool $overwriteValue Whether to override the "value" member
299 * @return $this
300 */
301 public function merge( $other, $overwriteValue = false ) {
302 if ( $this->statusData !== null && $other->statusData !== null ) {
303 throw new RuntimeException( "Status cannot be merged, because they both have \$statusData" );
304 } else {
305 $this->statusData ??= $other->statusData;
306 }
307
308 foreach ( $other->errors as $error ) {
309 $this->addError( $error );
310 }
311 $this->ok = $this->ok && $other->ok;
312 if ( $overwriteValue ) {
313 $this->value = $other->value;
314 }
315 $this->successCount += $other->successCount;
316 $this->failCount += $other->failCount;
317
318 return $this;
319 }
320
321 /**
322 * Returns a list of status messages of the given type
323 *
324 * Each entry is a map of:
325 * - message: string message key or MessageSpecifier
326 * - params: array list of parameters
327 *
328 * @deprecated since 1.43 Use `->getMessages( $type )` instead
329 * @param string $type
330 * @return array[]
331 * @phan-return array{type:'warning'|'error', message:string|MessageSpecifier, params:array}[]
332 */
333 public function getErrorsByType( $type ) {
334 $result = [];
335 foreach ( $this->errors as $error ) {
336 if ( $error['type'] === $type ) {
337 $result[] = $error;
338 }
339 }
340
341 return $result;
342 }
343
344 /**
345 * Returns a list of error messages, optionally only those of the given type
346 *
347 * If the `warning()` or `error()` method was called with a MessageSpecifier object,
348 * this method is guaranteed to return the same object.
349 *
350 * @since 1.43
351 * @param ?string $type If provided, only return messages of the type 'warning' or 'error'
352 * @phan-param null|'warning'|'error' $type
353 * @return MessageSpecifier[]
354 */
355 public function getMessages( ?string $type = null ): array {
356 Assert::parameter( $type === null || $type === 'warning' || $type === 'error',
357 '$type', "must be null, 'warning', or 'error'" );
358 $result = [];
359 foreach ( $this->errors as $error ) {
360 if ( $type === null || $error['type'] === $type ) {
361 [ 'message' => $key, 'params' => $params ] = $error;
362 if ( $key instanceof MessageSpecifier ) {
363 $result[] = $key;
364 } else {
365 $result[] = new MessageValue( $key, $params );
366 }
367 }
368 }
369
370 return $result;
371 }
372
373 /**
374 * Returns true if the specified message is present as a warning or error.
375 * Any message using the same key will be found (ignoring the message parameters).
376 *
377 * @param string $message Message key to search for
378 * (this parameter used to allow MessageSpecifier too, deprecated since 1.43)
379 * @return bool
380 */
381 public function hasMessage( $message ) {
382 if ( $message instanceof MessageSpecifier ) {
383 wfDeprecatedMsg( 'Passing MessageSpecifier to hasMessage()' .
384 ' was deprecated in MediaWiki 1.43', '1.43' );
385 $message = $message->getKey();
386 }
387
388 foreach ( $this->errors as [ 'message' => $key ] ) {
389 if ( ( $key instanceof MessageSpecifier && $key->getKey() === $message ) ||
390 $key === $message
391 ) {
392 return true;
393 }
394 }
395
396 return false;
397 }
398
399 /**
400 * Returns true if any other message than the specified ones is present as a warning or error.
401 * Any messages using the same keys will be found (ignoring the message parameters).
402 *
403 * @param string ...$messages Message keys to search for
404 * (this parameter used to allow MessageSpecifier too, deprecated since 1.43)
405 * @return bool
406 */
407 public function hasMessagesExcept( ...$messages ) {
408 $exceptedKeys = [];
409 foreach ( $messages as $message ) {
410 if ( $message instanceof MessageSpecifier ) {
411 wfDeprecatedMsg( 'Passing MessageSpecifier to hasMessagesExcept()' .
412 ' was deprecated in MediaWiki 1.43', '1.43' );
413 $message = $message->getKey();
414 }
415 $exceptedKeys[] = $message;
416 }
417
418 foreach ( $this->errors as [ 'message' => $key ] ) {
419 if ( $key instanceof MessageSpecifier ) {
420 $key = $key->getKey();
421 }
422 if ( !in_array( $key, $exceptedKeys, true ) ) {
423 return true;
424 }
425 }
426
427 return false;
428 }
429
430 /**
431 * If the specified source message exists, replace it with the specified
432 * destination message, but keep the same parameters as in the original error.
433 *
434 * When using a string as the `$source` parameter, any message using the same key will be replaced
435 * (regardless of whether it was stored as string or as MessageSpecifier, and ignoring the
436 * message parameters).
437 *
438 * When using a MessageSpecifier as the `$source` parameter, the message will only be replaced
439 * when the same MessageSpecifier object was stored in the StatusValue (compared with `===`).
440 * Since the only reliable way to obtain one is to use getErrors(), which is deprecated,
441 * passing a MessageSpecifier is deprecated (since 1.43).
442 *
443 * @param string $source Message key to search for
444 * (this parameter used to allow MessageSpecifier too, deprecated since 1.43)
445 * @param MessageSpecifier|string $dest Replacement message key or object
446 * @return bool Return true if the replacement was done, false otherwise.
447 */
448 public function replaceMessage( $source, $dest ) {
449 $replaced = false;
450
451 if ( $source instanceof MessageSpecifier ) {
452 wfDeprecatedMsg( 'Passing MessageSpecifier as $source to replaceMessage()' .
453 ' was deprecated in MediaWiki 1.43', '1.43' );
454 }
455
456 foreach ( $this->errors as [ 'message' => &$message, 'params' => &$params ] ) {
457 if ( $message === $source ||
458 ( $message instanceof MessageSpecifier && $message->getKey() === $source )
459 ) {
460 $message = $dest;
461 if ( $dest instanceof MessageSpecifier ) {
462 // 'params' will be ignored now, so remove them from the internal array
463 $params = [];
464 }
465 $replaced = true;
466 }
467 }
468
469 return $replaced;
470 }
471
472 /**
473 * Returns a string representation of the status for debugging.
474 * This is fairly verbose and may change without notice.
475 *
476 * @return string
477 */
478 public function __toString() {
479 $status = $this->isOK() ? "OK" : "Error";
480 if ( count( $this->errors ) ) {
481 $errorcount = "collected " . ( count( $this->errors ) ) . " message(s) on the way";
482 } else {
483 $errorcount = "no errors detected";
484 }
485 if ( isset( $this->value ) ) {
486 $valstr = get_debug_type( $this->value ) . " value set";
487 } else {
488 $valstr = "no value set";
489 }
490 $out = sprintf( "<%s, %s, %s>",
491 $status,
492 $errorcount,
493 $valstr
494 );
495 if ( count( $this->errors ) > 0 ) {
496 $hdr = sprintf( "+-%'-8s-+-%'-25s-+-%'-36s-+\n", "", "", "" );
497 $out .= "\n" . $hdr;
498 foreach ( $this->errors as [ 'type' => $type, 'message' => $key, 'params' => $params ] ) {
499 if ( $key instanceof MessageSpecifier ) {
500 $params = $key->getParams();
501 $key = $key->getKey();
502 }
503
504 $keyChunks = mb_str_split( $key, 25 );
505 $paramsChunks = mb_str_split( $this->flattenParams( $params, " | " ), 36 );
506
507 // array_map(null,...) is like Python's zip()
508 foreach ( array_map( null, [ $type ], $keyChunks, $paramsChunks )
509 as [ $typeChunk, $keyChunk, $paramsChunk ]
510 ) {
511 $out .= sprintf( "| %-8s | %-25s | %-36s |\n",
512 $typeChunk,
513 $keyChunk,
514 $paramsChunk
515 );
516 }
517 }
518 $out .= $hdr;
519 }
520
521 return $out;
522 }
523
524 /**
525 * @param array $params Message parameters
526 * @param string $joiner
527 *
528 * @return string String representation
529 */
530 private function flattenParams( array $params, string $joiner = ', ' ): string {
531 $ret = [];
532 foreach ( $params as $p ) {
533 if ( is_array( $p ) ) {
534 $r = '[ ' . self::flattenParams( $p ) . ' ]';
535 } elseif ( $p instanceof MessageSpecifier ) {
536 $r = '{ ' . $p->getKey() . ': ' . self::flattenParams( $p->getParams() ) . ' }';
537 } elseif ( $p instanceof MessageParam ) {
538 $r = $p->dump();
539 } else {
540 $r = (string)$p;
541 }
542
543 $ret[] = mb_strlen( $r ) > 100 ? mb_substr( $r, 0, 99 ) . "..." : $r;
544 }
545 return implode( $joiner, $ret );
546 }
547
548 /**
549 * Returns a list of status messages of the given type (or all if false)
550 *
551 * @internal Only for use by Status.
552 *
553 * @param string|bool $type
554 * @return array[]
555 */
556 protected function getStatusArray( $type = false ) {
557 $result = [];
558
559 foreach ( $this->getErrors() as $error ) {
560 if ( !$type || $error['type'] === $type ) {
561 if ( $error['message'] instanceof MessageSpecifier ) {
562 $result[] = [ $error['message']->getKey(), ...$error['message']->getParams() ];
563 } else {
564 $result[] = [ $error['message'], ...$error['params'] ];
565 }
566 }
567 }
568
569 return $result;
570 }
571 }