MediaWiki master
StatusValue.php
Go to the documentation of this file.
1<?php
23use Wikimedia\Assert\Assert;
25
49class StatusValue implements Stringable {
50
55 protected $ok = true;
56
63 protected $errors = [];
64
66 public $value;
67
69 public $success = [];
70
72 public $successCount = 0;
73
75 public $failCount = 0;
76
79
87 public static function newFatal( $message, ...$parameters ) {
88 $result = new static();
89 $result->fatal( $message, ...$parameters );
90 return $result;
91 }
92
99 public static function newGood( $value = null ) {
100 $result = new static();
101 $result->value = $value;
102 return $result;
103 }
104
116 public function splitByErrorType() {
117 $errorsOnlyStatusValue = static::newGood();
118 $warningsOnlyStatusValue = static::newGood();
119 $warningsOnlyStatusValue->setResult( true, $this->getValue() );
120 $errorsOnlyStatusValue->setResult( $this->isOK(), $this->getValue() );
121
122 foreach ( $this->errors as $item ) {
123 if ( $item['type'] === 'warning' ) {
124 $warningsOnlyStatusValue->errors[] = $item;
125 } else {
126 $errorsOnlyStatusValue->errors[] = $item;
127 }
128 }
129
130 return [ $errorsOnlyStatusValue, $warningsOnlyStatusValue ];
131 }
132
139 public function isGood() {
140 return $this->ok && !$this->errors;
141 }
142
148 public function isOK() {
149 return $this->ok;
150 }
151
155 public function getValue() {
156 return $this->value;
157 }
158
168 public function getErrors() {
169 return $this->errors;
170 }
171
178 public function setOK( $ok ) {
179 $this->ok = $ok;
180 return $this;
181 }
182
190 public function setResult( $ok, $value = null ) {
191 $this->ok = (bool)$ok;
192 $this->value = $value;
193 return $this;
194 }
195
213 private function addError( array $newError ) {
214 [ 'type' => $newType, 'message' => $newKey, 'params' => $newParams ] = $newError;
215 if ( $newKey instanceof MessageSpecifier ) {
216 if ( $newParams ) {
217 // Deprecate code like `Status::newFatal( wfMessage( 'foo' ), 'param' )`
218 // - the parameters have always been ignored, so this is usually a mistake.
219 wfDeprecatedMsg( 'Combining MessageSpecifier and parameters array' .
220 ' was deprecated in MediaWiki 1.43', '1.43' );
221 }
222 $newParams = $newKey->getParams();
223 $newKey = $newKey->getKey();
224 }
225
226 foreach ( $this->errors as [ 'type' => &$type, 'message' => $key, 'params' => $params ] ) {
227 if ( $key instanceof MessageSpecifier ) {
228 $params = $key->getParams();
229 $key = $key->getKey();
230 }
231 if ( $newKey === $key && $newParams === $params ) {
232 if ( $type === 'warning' && $newType === 'error' ) {
233 $type = 'error';
234 }
235 return $this;
236 }
237 }
238
239 $this->errors[] = $newError;
240
241 return $this;
242 }
243
251 public function warning( $message, ...$parameters ) {
252 $message = $this->normalizeMessage( $message );
253
254 return $this->addError( [
255 'type' => 'warning',
256 'message' => $message,
257 'params' => $parameters
258 ] );
259 }
260
269 public function error( $message, ...$parameters ) {
270 $message = $this->normalizeMessage( $message );
271
272 return $this->addError( [
273 'type' => 'error',
274 'message' => $message,
275 'params' => $parameters
276 ] );
277 }
278
287 public function fatal( $message, ...$parameters ) {
288 $this->ok = false;
289 return $this->error( $message, ...$parameters );
290 }
291
299 public function merge( $other, $overwriteValue = false ) {
300 if ( $this->statusData !== null && $other->statusData !== null ) {
301 throw new RuntimeException( "Status cannot be merged, because they both have \$statusData" );
302 } else {
303 $this->statusData ??= $other->statusData;
304 }
305
306 foreach ( $other->errors as $error ) {
307 $this->addError( $error );
308 }
309 $this->ok = $this->ok && $other->ok;
310 if ( $overwriteValue ) {
311 $this->value = $other->value;
312 }
313 $this->successCount += $other->successCount;
314 $this->failCount += $other->failCount;
315
316 return $this;
317 }
318
331 public function getErrorsByType( $type ) {
332 $result = [];
333 foreach ( $this->errors as $error ) {
334 if ( $error['type'] === $type ) {
335 $result[] = $error;
336 }
337 }
338
339 return $result;
340 }
341
350 public function getMessages( ?string $type = null ): array {
351 Assert::parameter( $type === null || $type === 'warning' || $type === 'error',
352 '$type', "must be null, 'warning', or 'error'" );
353 $result = [];
354 foreach ( $this->errors as $error ) {
355 if ( $type === null || $error['type'] === $type ) {
356 [ 'message' => $key, 'params' => $params ] = $error;
357 if ( $key instanceof MessageSpecifier ) {
358 $result[] = $key;
359 } else {
360 // TODO: Make MessageValue implement MessageSpecifier, and use a MessageValue here
361 $result[] = new Message( $key, $params );
362 }
363 }
364 }
365
366 return $result;
367 }
368
377 public function hasMessage( $message ) {
378 if ( $message instanceof MessageSpecifier ) {
379 wfDeprecatedMsg( 'Passing MessageSpecifier to hasMessage()' .
380 ' was deprecated in MediaWiki 1.43', '1.43' );
381 $message = $message->getKey();
382 } elseif ( $message instanceof MessageValue ) {
383 wfDeprecatedMsg( 'Passing MessageValue 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
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 } elseif ( $message instanceof MessageValue ) {
415 wfDeprecatedMsg( 'Passing MessageValue to hasMessagesExcept()' .
416 ' was deprecated in MediaWiki 1.43', '1.43' );
417 $message = $message->getKey();
418 }
419 $exceptedKeys[] = $message;
420 }
421
422 foreach ( $this->errors as [ 'message' => $key ] ) {
423 if ( $key instanceof MessageSpecifier ) {
424 $key = $key->getKey();
425 }
426 if ( !in_array( $key, $exceptedKeys, true ) ) {
427 return true;
428 }
429 }
430
431 return false;
432 }
433
455 public function replaceMessage( $source, $dest ) {
456 $replaced = false;
457
458 if ( $source instanceof MessageSpecifier ) {
459 wfDeprecatedMsg( 'Passing MessageSpecifier as $source to replaceMessage()' .
460 ' was deprecated in MediaWiki 1.43', '1.43' );
461 } elseif ( $source instanceof MessageValue ) {
462 wfDeprecatedMsg( 'Passing MessageValue as $source to replaceMessage()' .
463 ' was deprecated in MediaWiki 1.43', '1.43' );
464 $source = $this->normalizeMessage( $source );
465 }
466
467 $dest = $this->normalizeMessage( $dest );
468
469 foreach ( $this->errors as [ 'message' => &$message, 'params' => &$params ] ) {
470 if ( $message === $source ||
471 ( $message instanceof MessageSpecifier && $message->getKey() === $source )
472 ) {
473 $message = $dest;
474 if ( $dest instanceof MessageSpecifier ) {
475 // 'params' will be ignored now, so remove them from the internal array
476 $params = [];
477 }
478 $replaced = true;
479 }
480 }
481
482 return $replaced;
483 }
484
491 public function __toString() {
492 $status = $this->isOK() ? "OK" : "Error";
493 if ( count( $this->errors ) ) {
494 $errorcount = "collected " . ( count( $this->errors ) ) . " message(s) on the way";
495 } else {
496 $errorcount = "no errors detected";
497 }
498 if ( isset( $this->value ) ) {
499 $valstr = gettype( $this->value ) . " value set";
500 if ( is_object( $this->value ) ) {
501 $valstr .= "\"" . get_class( $this->value ) . "\" instance";
502 }
503 } else {
504 $valstr = "no value set";
505 }
506 $out = sprintf( "<%s, %s, %s>",
507 $status,
508 $errorcount,
509 $valstr
510 );
511 if ( count( $this->errors ) > 0 ) {
512 $hdr = sprintf( "+-%'-8s-+-%'-25s-+-%'-36s-+\n", "", "", "" );
513 $out .= "\n" . $hdr;
514 foreach ( $this->errors as [ 'type' => $type, 'message' => $key, 'params' => $params ] ) {
515 if ( $key instanceof MessageSpecifier ) {
516 $params = $key->getParams();
517 $key = $key->getKey();
518 }
519
520 $keyChunks = mb_str_split( $key, 25 );
521 $paramsChunks = mb_str_split( $this->flattenParams( $params, " | " ), 36 );
522
523 // array_map(null,...) is like Python's zip()
524 foreach ( array_map( null, [ $type ], $keyChunks, $paramsChunks )
525 as [ $typeChunk, $keyChunk, $paramsChunk ]
526 ) {
527 $out .= sprintf( "| %-8s | %-25s | %-36s |\n",
528 $typeChunk,
529 $keyChunk,
530 $paramsChunk
531 );
532 }
533 }
534 $out .= $hdr;
535 }
536
537 return $out;
538 }
539
546 private function flattenParams( array $params, string $joiner = ', ' ): string {
547 $ret = [];
548 foreach ( $params as $p ) {
549 if ( is_array( $p ) ) {
550 $r = '[ ' . self::flattenParams( $p ) . ' ]';
551 } elseif ( $p instanceof MessageSpecifier ) {
552 $r = '{ ' . $p->getKey() . ': ' . self::flattenParams( $p->getParams() ) . ' }';
553 } else {
554 $r = (string)$p;
555 }
556
557 $ret[] = mb_strlen( $r ) > 100 ? mb_substr( $r, 0, 99 ) . "..." : $r;
558 }
559 return implode( $joiner, $ret );
560 }
561
570 protected function getStatusArray( $type = false ) {
571 $result = [];
572
573 foreach ( $this->getErrors() as $error ) {
574 if ( !$type || $error['type'] === $type ) {
575 if ( $error['message'] instanceof MessageSpecifier ) {
576 $result[] = [ $error['message']->getKey(), ...$error['message']->getParams() ];
577 } else {
578 $result[] = [ $error['message'], ...$error['params'] ];
579 }
580 }
581 }
582
583 return $result;
584 }
585
591 private function normalizeMessage( $message ) {
592 if ( $message instanceof MessageValue ) {
593 $converter = new Converter();
594 return $converter->convertMessageValue( $message );
595 }
596
597 return $message;
598 }
599}
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
array $params
The job parameters.
Converter between Message and MessageValue.
Definition Converter.php:18
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:158
Generic operation result class Has warning/error list, boolean status and arbitrary value.
hasMessage( $message)
Returns true if the specified message is present as a warning or error.
static newFatal( $message,... $parameters)
Factory function for fatal errors.
int $failCount
Counter for batch operations.
array[] $errors
getErrors()
Get the list of errors.
getMessages(?string $type=null)
Returns a list of error messages, optionally only those of the given type.
replaceMessage( $source, $dest)
If the specified source message exists, replace it with the specified destination message,...
splitByErrorType()
Splits this StatusValue object into two new StatusValue objects, one which contains only the error me...
setOK( $ok)
Change operation status.
hasMessagesExcept(... $messages)
Returns true if any other message than the specified ones is present as a warning or error.
getStatusArray( $type=false)
Returns a list of status messages of the given type (or all if false)
isOK()
Returns whether the operation completed.
fatal( $message,... $parameters)
Add an error and set OK to false, indicating that the operation as a whole was fatal.
setResult( $ok, $value=null)
Change operation result.
merge( $other, $overwriteValue=false)
Merge another status object into this one.
mixed $statusData
arbitrary extra data about the operation
__toString()
Returns a string representation of the status for debugging.
error( $message,... $parameters)
Add an error, do not set fatal flag This can be used for non-fatal errors.
getErrorsByType( $type)
Returns a list of status messages of the given type.
warning( $message,... $parameters)
Add a new warning.
isGood()
Returns whether the operation completed and didn't have any error or warnings.
static newGood( $value=null)
Factory function for good results.
int $successCount
Counter for batch operations.
Value object representing a message for i18n.
getKey()
Returns the message key.
$source