MediaWiki master
StatusValue.php
Go to the documentation of this file.
1<?php
23use Wikimedia\Assert\Assert;
25
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 if ( $newError[ 'message' ] instanceof MessageSpecifier ) {
215 $isEqual = static function ( $key, $params ) use ( $newError ) {
216 if ( $key instanceof MessageSpecifier ) {
217 // compare attributes of both MessageSpecifiers
218 return $newError['message'] == $key;
219 } else {
220 return $newError['message']->getKey() === $key &&
221 $newError['message']->getParams() === $params;
222 }
223 };
224 } else {
225 $isEqual = static function ( $key, $params ) use ( $newError ) {
226 if ( $key instanceof MessageSpecifier ) {
227 $params = $key->getParams();
228 $key = $key->getKey();
229 }
230 return $newError['message'] === $key && $newError['params'] === $params;
231 };
232 }
233 foreach ( $this->errors as [ 'type' => &$type, 'message' => $key, 'params' => $params ] ) {
234 if ( $isEqual( $key, $params ) ) {
235 if ( $type === 'warning' && $newError['type'] === 'error' ) {
236 $type = 'error';
237 }
238 return $this;
239 }
240 }
241 $this->errors[] = $newError;
242 return $this;
243 }
244
252 public function warning( $message, ...$parameters ) {
253 $message = $this->normalizeMessage( $message );
254
255 return $this->addError( [
256 'type' => 'warning',
257 'message' => $message,
258 'params' => $parameters
259 ] );
260 }
261
270 public function error( $message, ...$parameters ) {
271 $message = $this->normalizeMessage( $message );
272
273 return $this->addError( [
274 'type' => 'error',
275 'message' => $message,
276 'params' => $parameters
277 ] );
278 }
279
288 public function fatal( $message, ...$parameters ) {
289 $this->ok = false;
290 return $this->error( $message, ...$parameters );
291 }
292
300 public function merge( $other, $overwriteValue = false ) {
301 if ( $this->statusData !== null && $other->statusData !== null ) {
302 throw new RuntimeException( "Status cannot be merged, because they both have \$statusData" );
303 } else {
304 $this->statusData ??= $other->statusData;
305 }
306
307 foreach ( $other->errors as $error ) {
308 $this->addError( $error );
309 }
310 $this->ok = $this->ok && $other->ok;
311 if ( $overwriteValue ) {
312 $this->value = $other->value;
313 }
314 $this->successCount += $other->successCount;
315 $this->failCount += $other->failCount;
316
317 return $this;
318 }
319
332 public function getErrorsByType( $type ) {
333 $result = [];
334 foreach ( $this->errors as $error ) {
335 if ( $error['type'] === $type ) {
336 $result[] = $error;
337 }
338 }
339
340 return $result;
341 }
342
351 public function getMessages( ?string $type = null ): array {
352 Assert::parameter( $type === null || $type === 'warning' || $type === 'error',
353 '$type', "must be null, 'warning', or 'error'" );
354 $result = [];
355 foreach ( $this->errors as $error ) {
356 if ( $type === null || $error['type'] === $type ) {
357 [ 'message' => $key, 'params' => $params ] = $error;
358 if ( $key instanceof MessageSpecifier ) {
359 $result[] = $key;
360 } else {
361 // TODO: Make MessageValue implement MessageSpecifier, and use a MessageValue here
362 $result[] = new Message( $key, $params );
363 }
364 }
365 }
366
367 return $result;
368 }
369
377 public function hasMessage( $message ) {
378 if ( $message instanceof MessageSpecifier || $message instanceof MessageValue ) {
379 $message = $message->getKey();
380 }
381
382 foreach ( $this->errors as [ 'message' => $key ] ) {
383 if ( ( $key instanceof MessageSpecifier && $key->getKey() === $message ) ||
384 $key === $message
385 ) {
386 return true;
387 }
388 }
389
390 return false;
391 }
392
400 public function hasMessagesExcept( ...$messages ) {
401 $exceptedKeys = [];
402 foreach ( $messages as $message ) {
403 if ( $message instanceof MessageSpecifier || $message instanceof MessageValue ) {
404 $message = $message->getKey();
405 }
406 $exceptedKeys[] = $message;
407 }
408
409 foreach ( $this->errors as [ 'message' => $key ] ) {
410 if ( $key instanceof MessageSpecifier ) {
411 $key = $key->getKey();
412 }
413 if ( !in_array( $key, $exceptedKeys, true ) ) {
414 return true;
415 }
416 }
417
418 return false;
419 }
420
432 public function replaceMessage( $source, $dest ) {
433 $replaced = false;
434
435 $source = $this->normalizeMessage( $source );
436 $dest = $this->normalizeMessage( $dest );
437
438 foreach ( $this->errors as [ 'message' => &$message ] ) {
439 if ( $message === $source ||
440 ( $message instanceof MessageSpecifier && $message->getKey() === $source )
441 ) {
442 $message = $dest;
443 $replaced = true;
444 }
445 }
446
447 return $replaced;
448 }
449
456 public function __toString() {
457 $status = $this->isOK() ? "OK" : "Error";
458 if ( count( $this->errors ) ) {
459 $errorcount = "collected " . ( count( $this->errors ) ) . " message(s) on the way";
460 } else {
461 $errorcount = "no errors detected";
462 }
463 if ( isset( $this->value ) ) {
464 $valstr = gettype( $this->value ) . " value set";
465 if ( is_object( $this->value ) ) {
466 $valstr .= "\"" . get_class( $this->value ) . "\" instance";
467 }
468 } else {
469 $valstr = "no value set";
470 }
471 $out = sprintf( "<%s, %s, %s>",
472 $status,
473 $errorcount,
474 $valstr
475 );
476 if ( count( $this->errors ) > 0 ) {
477 $hdr = sprintf( "+-%'-8s-+-%'-25s-+-%'-36s-+\n", "", "", "" );
478 $out .= "\n" . $hdr;
479 foreach ( $this->errors as [ 'type' => $type, 'message' => $key, 'params' => $params ] ) {
480 if ( $key instanceof MessageSpecifier ) {
481 $params = $key->getParams();
482 $key = $key->getKey();
483 }
484
485 $keyChunks = mb_str_split( $key, 25 );
486 $paramsChunks = mb_str_split( $this->flattenParams( $params, " | " ), 36 );
487
488 // array_map(null,...) is like Python's zip()
489 foreach ( array_map( null, [ $type ], $keyChunks, $paramsChunks )
490 as [ $typeChunk, $keyChunk, $paramsChunk ]
491 ) {
492 $out .= sprintf( "| %-8s | %-25s | %-36s |\n",
493 $typeChunk,
494 $keyChunk,
495 $paramsChunk
496 );
497 }
498 }
499 $out .= $hdr;
500 }
501
502 return $out;
503 }
504
511 private function flattenParams( array $params, string $joiner = ', ' ): string {
512 $ret = [];
513 foreach ( $params as $p ) {
514 if ( is_array( $p ) ) {
515 $r = '[ ' . self::flattenParams( $p ) . ' ]';
516 } elseif ( $p instanceof MessageSpecifier ) {
517 $r = '{ ' . $p->getKey() . ': ' . self::flattenParams( $p->getParams() ) . ' }';
518 } else {
519 $r = (string)$p;
520 }
521
522 $ret[] = mb_strlen( $r ) > 100 ? mb_substr( $r, 0, 99 ) . "..." : $r;
523 }
524 return implode( $joiner, $ret );
525 }
526
536 protected function getStatusArray( $type = false ) {
537 $result = [];
538
539 foreach ( $this->getErrors() as $error ) {
540 if ( !$type || $error['type'] === $type ) {
541 if ( $error['message'] instanceof MessageSpecifier ) {
542 $result[] = [ $error['message']->getKey(), ...$error['message']->getParams() ];
543 } else {
544 $result[] = [ $error['message'], ...$error['params'] ];
545 }
546 }
547 }
548
549 return $result;
550 }
551
557 private function normalizeMessage( $message ) {
558 if ( $message instanceof MessageValue ) {
559 $converter = new Converter();
560 return $converter->convertMessageValue( $message );
561 }
562
563 return $message;
564 }
565}
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