MediaWiki master
StatusValue.php
Go to the documentation of this file.
1<?php
6
7use Wikimedia\Assert\Assert;
8use Wikimedia\JsonCodec\Hint;
9use Wikimedia\JsonCodec\HintType;
10use Wikimedia\JsonCodec\JsonCodecable;
11use Wikimedia\JsonCodec\JsonCodecableTrait;
15
45class StatusValue implements JsonCodecable, Stringable {
46 use JsonCodecableTrait;
47
52 protected $ok = true;
53
60 protected $errors = [];
61
63 public $value;
64
66 public $success = [];
67
69 public $successCount = 0;
70
72 public $failCount = 0;
73
76
80 public function __construct() {
81 }
82
91 public static function newFatal( $message, ...$parameters ): static {
92 $result = new static();
93 $result->fatal( $message, ...$parameters );
94 return $result;
95 }
96
102 public static function newGood( $value = null ): static {
103 $result = new static();
104 $result->value = $value;
105 return $result;
106 }
107
138 public static function cast( StatusValue $sv ) {
139 if ( $sv instanceof static ) {
140 return $sv;
141 }
142
143 $result = new static();
144 $result->ok = $sv->ok;
145 $result->errors = $sv->errors;
146 $result->value = $sv->value;
147 $result->successCount = $sv->successCount;
148 $result->failCount = $sv->failCount;
149 $result->success = $sv->success;
150 $result->statusData = $sv->statusData;
151
152 return $result;
153 }
154
166 public function splitByErrorType() {
167 $errorsOnlyStatusValue = static::newGood();
168 $warningsOnlyStatusValue = static::newGood();
169 $warningsOnlyStatusValue->setResult( true, $this->getValue() );
170 $errorsOnlyStatusValue->setResult( $this->isOK(), $this->getValue() );
171
172 foreach ( $this->errors as $item ) {
173 if ( $item['type'] === 'warning' ) {
174 $warningsOnlyStatusValue->errors[] = $item;
175 } else {
176 $errorsOnlyStatusValue->errors[] = $item;
177 }
178 }
179
180 return [ $errorsOnlyStatusValue, $warningsOnlyStatusValue ];
181 }
182
189 public function isGood() {
190 return $this->ok && !$this->errors;
191 }
192
198 public function isOK() {
199 return $this->ok;
200 }
201
205 public function getValue() {
206 return $this->value;
207 }
208
218 public function getErrors() {
219 return $this->errors;
220 }
221
228 public function setOK( $ok ) {
229 $this->ok = $ok;
230 return $this;
231 }
232
242 public function setResult( $ok, $value = null ) {
243 $this->ok = (bool)$ok;
244 $this->value = $value;
245 return $this;
246 }
247
265 private function addError( array $newError ) {
266 [ 'type' => $newType, 'message' => $newKey, 'params' => $newParams ] = $newError;
267 if ( $newKey instanceof MessageSpecifier ) {
268 Assert::parameter( $newParams === [],
269 '$parameters', "must be empty when using a MessageSpecifier" );
270 $newParams = $newKey->getParams();
271 $newKey = $newKey->getKey();
272 }
273
274 foreach ( $this->errors as [ 'type' => &$type, 'message' => $key, 'params' => $params ] ) {
275 if ( $key instanceof MessageSpecifier ) {
276 $params = $key->getParams();
277 $key = $key->getKey();
278 }
279
280 // This uses loose equality as we must support equality between MessageParam objects
281 // (e.g. ScalarParam), including when they are created separate and not by-ref equal.
282 if ( $newKey === $key && $newParams == $params ) {
283 if ( $type === 'warning' && $newType === 'error' ) {
284 $type = 'error';
285 }
286 return $this;
287 }
288 }
289
290 $this->errors[] = $newError;
291
292 return $this;
293 }
294
304 public function warning( $message, ...$parameters ) {
305 return $this->addError( [
306 'type' => 'warning',
307 'message' => $message,
308 'params' => $parameters
309 ] );
310 }
311
322 public function error( $message, ...$parameters ) {
323 return $this->addError( [
324 'type' => 'error',
325 'message' => $message,
326 'params' => $parameters
327 ] );
328 }
329
340 public function fatal( $message, ...$parameters ) {
341 $this->ok = false;
342 return $this->error( $message, ...$parameters );
343 }
344
352 public function merge( $other, $overwriteValue = false ) {
353 if ( $this->statusData !== null &&
354 $other->statusData !== null &&
355 // Nothing to worry about when the values are identical anyway
356 $this->statusData !== $other->statusData
357 ) {
358 throw new RuntimeException( "Status cannot be merged, because they both have \$statusData" );
359 } else {
360 $this->statusData ??= $other->statusData;
361 }
362
363 foreach ( $other->errors as $error ) {
364 $this->addError( $error );
365 }
366 $this->ok = $this->ok && $other->ok;
367 if ( $overwriteValue ) {
368 $this->value = $other->value;
369 }
370 $this->successCount += $other->successCount;
371 $this->failCount += $other->failCount;
372
373 return $this;
374 }
375
388 public function getErrorsByType( $type ) {
389 $result = [];
390 foreach ( $this->errors as $error ) {
391 if ( $error['type'] === $type ) {
392 $result[] = $error;
393 }
394 }
395
396 return $result;
397 }
398
410 public function getMessages( ?string $type = null ): array {
411 Assert::parameter( $type === null || $type === 'warning' || $type === 'error',
412 '$type', "must be null, 'warning', or 'error'" );
413 $result = [];
414 foreach ( $this->errors as $error ) {
415 if ( $type === null || $error['type'] === $type ) {
416 [ 'message' => $key, 'params' => $params ] = $error;
417 if ( $key instanceof MessageSpecifier ) {
418 $result[] = $key;
419 } else {
420 $result[] = new MessageValue( $key, $params );
421 }
422 }
423 }
424
425 return $result;
426 }
427
435 public function hasMessage( string $message ) {
436 foreach ( $this->errors as [ 'message' => $key ] ) {
437 if ( ( $key instanceof MessageSpecifier && $key->getKey() === $message ) ||
438 $key === $message
439 ) {
440 return true;
441 }
442 }
443
444 return false;
445 }
446
454 public function hasMessagesExcept( string ...$messages ) {
455 foreach ( $this->errors as [ 'message' => $key ] ) {
456 if ( $key instanceof MessageSpecifier ) {
457 $key = $key->getKey();
458 }
459 if ( !in_array( $key, $messages, true ) ) {
460 return true;
461 }
462 }
463
464 return false;
465 }
466
477 public function replaceMessage( string $source, $dest ) {
478 $replaced = false;
479
480 foreach ( $this->errors as [ 'message' => &$message, 'params' => &$params ] ) {
481 if ( $message === $source ||
482 ( $message instanceof MessageSpecifier && $message->getKey() === $source )
483 ) {
484 $message = $dest;
485 if ( $dest instanceof MessageSpecifier ) {
486 // 'params' will be ignored now, so remove them from the internal array
487 $params = [];
488 }
489 $replaced = true;
490 }
491 }
492
493 return $replaced;
494 }
495
502 public function __toString() {
503 $status = $this->isOK() ? "OK" : "Error";
504 if ( count( $this->errors ) ) {
505 $errorcount = "collected " . ( count( $this->errors ) ) . " message(s) on the way";
506 } else {
507 $errorcount = "no errors detected";
508 }
509 if ( $this->value !== null ) {
510 $valstr = get_debug_type( $this->value ) . " value set";
511 } else {
512 $valstr = "no value set";
513 }
514 $out = sprintf( "<%s, %s, %s>",
515 $status,
516 $errorcount,
517 $valstr
518 );
519 if ( count( $this->errors ) > 0 ) {
520 $hdr = sprintf( "+-%'-8s-+-%'-25s-+-%'-36s-+\n", "", "", "" );
521 $out .= "\n" . $hdr;
522 foreach ( $this->errors as [ 'type' => $type, 'message' => $key, 'params' => $params ] ) {
523 if ( $key instanceof MessageSpecifier ) {
524 $params = $key->getParams();
525 $key = $key->getKey();
526 }
527
528 $keyChunks = mb_str_split( $key, 25 );
529 $paramsChunks = mb_str_split( $this->flattenParams( $params, " | " ), 36 );
530
531 // array_map(null,...) is like Python's zip()
532 foreach ( array_map( null, [ $type ], $keyChunks, $paramsChunks )
533 as [ $typeChunk, $keyChunk, $paramsChunk ]
534 ) {
535 $out .= sprintf( "| %-8s | %-25s | %-36s |\n",
536 $typeChunk,
537 $keyChunk,
538 $paramsChunk
539 );
540 }
541 }
542 $out .= $hdr;
543 }
544
545 return $out;
546 }
547
554 private function flattenParams( array $params, string $joiner = ', ' ): string {
555 $ret = [];
556 foreach ( $params as $p ) {
557 if ( is_array( $p ) ) {
558 $r = '[ ' . self::flattenParams( $p ) . ' ]';
559 } elseif ( $p instanceof MessageSpecifier ) {
560 $r = '{ ' . $p->getKey() . ': ' . self::flattenParams( $p->getParams() ) . ' }';
561 } elseif ( $p instanceof MessageParam ) {
562 $r = $p->dump();
563 } else {
564 $r = (string)$p;
565 }
566
567 $ret[] = mb_strlen( $r ) > 100 ? mb_substr( $r, 0, 99 ) . "..." : $r;
568 }
569 return implode( $joiner, $ret );
570 }
571
580 protected function getStatusArray( $type = false ) {
581 $result = [];
582
583 foreach ( $this->getErrors() as $error ) {
584 if ( !$type || $error['type'] === $type ) {
585 if ( $error['message'] instanceof MessageSpecifier ) {
586 $result[] = [ $error['message']->getKey(), ...$error['message']->getParams() ];
587 } else {
588 $result[] = [ $error['message'], ...$error['params'] ];
589 }
590 }
591 }
592
593 return $result;
594 }
595
600 public function toJsonArray(): array {
601 $errors = [];
602 foreach ( $this->errors as $error ) {
603 if ( $error['message'] instanceof MessageValue ) {
604 $errorData = [ 'message' => $error['message'] ];
605 } elseif ( $error['message'] instanceof MessageSpecifier ) {
606 // Loose round trip
607 $errorData = [ 'message' => MessageValue::newFromSpecifier( $error['message'] ) ];
608 } else {
609 $errorData = [ 'message' => $error['message'] ];
610 if ( $error['params'] ) {
611 $errorData['params'] = $error['params'];
612 }
613 }
614 if ( $error['type'] !== 'error' ) {
615 $errorData['type'] = $error['type'];
616 }
617 $errors[] = $errorData;
618 }
619 $data = [ 'ok' => $this->ok ];
620 if ( $errors ) {
621 $data['errors'] = $errors;
622 }
623 if ( $this->value !== null ) {
624 $data['value'] = $this->value;
625 }
626 if ( $this->success ) {
627 $data['success'] = $this->success;
628 }
629 if ( $this->successCount ) {
630 $data['successCount'] = $this->successCount;
631 }
632 if ( $this->failCount ) {
633 $data['failCount'] = $this->failCount;
634 }
635 if ( $this->statusData !== null ) {
636 $data['statusData'] = $this->statusData;
637 }
638 return $data;
639 }
640
642 public static function newFromJsonArray( array $json ) {
643 $status = new static;
644 $status->ok = $json['ok'];
645
646 foreach ( $json['errors'] ?? [] as $error ) {
647 $status->errors[] = [
648 'type' => $error['type'] ?? 'error',
649 'message' => $error['message'],
650 'params' => $error['params'] ?? [],
651 ];
652 }
653 $status->value = $json['value'] ?? null;
654 $status->success = $json['success'] ?? [];
655 $status->successCount = $json['successCount'] ?? 0;
656 $status->failCount = $json['failCount'] ?? 0;
657 $status->statusData = $json['statusData'] ?? null;
658 return $status;
659 }
660
662 public static function jsonClassHintFor( string $keyName ) {
663 return match ( $keyName ) {
664 // @phan-suppress-next-line PhanUndeclaredClassReference -- it's an associative array
665 'errors' => Hint::build( 'array', HintType::LIST ),
666 default => null
667 };
668 }
669
670}
Generic operation result class Has warning/error list, boolean status and arbitrary value.
hasMessagesExcept(string ... $messages)
Returns true if any other message than the specified ones 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.
static newFromJsonArray(array $json)
splitByErrorType()
Splits this StatusValue object into two new StatusValue objects, one which contains only the error me...
setOK( $ok)
Change operation status.
static cast(StatusValue $sv)
Succinct helper method to wrap a StatusValue in some other specific subclass.
hasMessage(string $message)
Returns true if the specified message is present as a warning or error.
getStatusArray( $type=false)
Returns a list of status messages of the given type (or all if false).
replaceMessage(string $source, $dest)
If the specified source message exists, replace it with the specified destination message,...
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.
toJsonArray()
JSON serializing a StatusValue is possible only if the value and statusData are JSON-serializable,...
bool[] $success
Map of (key => bool) to indicate success of each part of batch operations.
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.
static jsonClassHintFor(string $keyName)
int $successCount
Counter for batch operations.
Value object representing a message parameter with one of the types from {.
Value object representing a message for i18n.
static newFromSpecifier(MessageSpecifier $spec)
Convert from any MessageSpecifier to a MessageValue.
getKey()
Returns the message key.
$source
array $params
The job parameters.