3 * Generic operation result.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Generic operation result class
25 * Has warning/error list, boolean status and arbitrary value
27 * "Good" means the operation was completed with no warnings or errors.
29 * "OK" means the operation was partially or wholly completed.
31 * An operation which is not OK should have errors so that the user can be
32 * informed as to what went wrong. Calling the fatal() function sets an error
33 * message and simultaneously switches off the OK flag.
35 * The recommended pattern for Status objects is to return a Status object
36 * unconditionally, i.e. both on success and on failure -- so that the
37 * developer of the calling code is reminded that the function can fail, and
38 * so that a lack of error-handling will be explicit.
41 /** @var StatusValue */
46 /** @var array Map of (key => bool) to indicate success of each part of batch operations */
48 /** @var int Counter for batch operations */
49 public $successCount = 0;
50 /** @var int Counter for batch operations */
51 public $failCount = 0;
54 public $cleanCallback = false;
57 * @param StatusValue $sv [optional]
59 public function __construct( StatusValue
$sv = null ) {
60 $this->sv
= ( $sv === null ) ?
new StatusValue() : $sv;
62 $this->value
=& $this->sv
->value
;
63 $this->successCount
=& $this->sv
->successCount
;
64 $this->failCount
=& $this->sv
->failCount
;
65 $this->success
=& $this->sv
->success
;
69 * Succinct helper method to wrap a StatusValue
71 * This is is useful when formatting StatusValue objects:
73 * $this->getOutput()->addHtml( Status::wrap( $sv )->getHTML() );
76 * @param StatusValue|Status $sv
79 public static function wrap( $sv ) {
80 return $sv instanceof Status ?
$sv : new self( $sv );
84 * Factory function for fatal errors
86 * @param string|Message $message Message name or object
89 public static function newFatal( $message /*, parameters...*/ ) {
90 return new self( call_user_func_array(
91 [ 'StatusValue', 'newFatal' ], func_get_args()
96 * Factory function for good results
101 public static function newGood( $value = null ) {
102 $sv = new StatusValue();
105 return new self( $sv );
109 * Splits this Status object into two new Status objects, one which contains only
110 * the error messages, and one that contains the warnings, only. The returned array is
113 * 0 => object(Status) # the Status with error messages, only
114 * 1 => object(Status) # The Status with warning messages, only
119 public function splitByErrorType() {
120 list( $errorsOnlyStatusValue, $warningsOnlyStatusValue ) = $this->sv
->splitByErrorType();
121 $errorsOnlyStatus = new Status( $errorsOnlyStatusValue );
122 $warningsOnlyStatus = new Status( $warningsOnlyStatusValue );
123 $errorsOnlyStatus->cleanCallback
= $warningsOnlyStatus->cleanCallback
= $this->cleanCallback
;
125 return [ $errorsOnlyStatus, $warningsOnlyStatus ];
129 * Change operation result
131 * @param bool $ok Whether the operation completed
132 * @param mixed $value
134 public function setResult( $ok, $value = null ) {
135 $this->sv
->setResult( $ok, $value );
139 * Returns the wrapped StatusValue object
140 * @return StatusValue
143 public function getStatusValue() {
148 * Returns whether the operation completed and didn't have any error or
153 public function isGood() {
154 return $this->sv
->isGood();
158 * Returns whether the operation completed
162 public function isOK() {
163 return $this->sv
->isOK();
169 * @param string|Message $message Message name or object
171 public function warning( $message /*, parameters... */ ) {
172 call_user_func_array( [ $this->sv
, 'warning' ], func_get_args() );
176 * Add an error, do not set fatal flag
177 * This can be used for non-fatal errors
179 * @param string|Message $message Message name or object
181 public function error( $message /*, parameters... */ ) {
182 call_user_func_array( [ $this->sv
, 'error' ], func_get_args() );
186 * Add an error and set OK to false, indicating that the operation
187 * as a whole was fatal
189 * @param string|Message $message Message name or object
191 public function fatal( $message /*, parameters... */ ) {
192 call_user_func_array( [ $this->sv
, 'fatal' ], func_get_args() );
196 * @param array $params
199 protected function cleanParams( array $params ) {
200 if ( !$this->cleanCallback
) {
204 foreach ( $params as $i => $param ) {
205 $cleanParams[$i] = call_user_func( $this->cleanCallback
, $param );
211 * @param string|Language|null $lang Language to use for processing
212 * messages, or null to default to the user language.
215 protected function languageFromParam( $lang ) {
218 if ( $lang === null ) {
219 // @todo: Use RequestContext::getMain()->getLanguage() instead
221 } elseif ( $lang instanceof Language ||
$lang instanceof StubUserLang
) {
224 return Language
::factory( $lang );
229 * Get the error list as a wikitext formatted list
231 * @param string|bool $shortContext A short enclosing context message name, to
232 * be used when there is a single error
233 * @param string|bool $longContext A long enclosing context message name, for a list
234 * @param string|Language $lang Language to use for processing messages
237 public function getWikiText( $shortContext = false, $longContext = false, $lang = null ) {
238 $lang = $this->languageFromParam( $lang );
240 $rawErrors = $this->sv
->getErrors();
241 if ( count( $rawErrors ) == 0 ) {
242 if ( $this->sv
->isOK() ) {
243 $this->sv
->fatal( 'internalerror_info',
244 __METHOD__
. " called for a good result, this is incorrect\n" );
246 $this->sv
->fatal( 'internalerror_info',
247 __METHOD__
. ": Invalid result object: no error text but not OK\n" );
249 $rawErrors = $this->sv
->getErrors(); // just added a fatal
251 if ( count( $rawErrors ) == 1 ) {
252 $s = $this->getErrorMessage( $rawErrors[0], $lang )->plain();
253 if ( $shortContext ) {
254 $s = wfMessage( $shortContext, $s )->inLanguage( $lang )->plain();
255 } elseif ( $longContext ) {
256 $s = wfMessage( $longContext, "* $s\n" )->inLanguage( $lang )->plain();
259 $errors = $this->getErrorMessageArray( $rawErrors, $lang );
260 foreach ( $errors as &$error ) {
261 $error = $error->plain();
263 $s = '* ' . implode( "\n* ", $errors ) . "\n";
264 if ( $longContext ) {
265 $s = wfMessage( $longContext, $s )->inLanguage( $lang )->plain();
266 } elseif ( $shortContext ) {
267 $s = wfMessage( $shortContext, "\n$s\n" )->inLanguage( $lang )->plain();
274 * Get a bullet list of the errors as a Message object.
276 * $shortContext and $longContext can be used to wrap the error list in some text.
277 * $shortContext will be preferred when there is a single error; $longContext will be
278 * preferred when there are multiple ones. In either case, $1 will be replaced with
279 * the list of errors.
281 * $shortContext is assumed to use $1 as an inline parameter: if there is a single item,
282 * it will not be made into a list; if there are multiple items, newlines will be inserted
284 * $longContext is assumed to use $1 as a standalone parameter; it will always receive a list.
286 * If both parameters are missing, and there is only one error, no bullet will be added.
288 * @param string|string[] $shortContext A message name or an array of message names.
289 * @param string|string[] $longContext A message name or an array of message names.
290 * @param string|Language $lang Language to use for processing messages
293 public function getMessage( $shortContext = false, $longContext = false, $lang = null ) {
294 $lang = $this->languageFromParam( $lang );
296 $rawErrors = $this->sv
->getErrors();
297 if ( count( $rawErrors ) == 0 ) {
298 if ( $this->sv
->isOK() ) {
299 $this->sv
->fatal( 'internalerror_info',
300 __METHOD__
. " called for a good result, this is incorrect\n" );
302 $this->sv
->fatal( 'internalerror_info',
303 __METHOD__
. ": Invalid result object: no error text but not OK\n" );
305 $rawErrors = $this->sv
->getErrors(); // just added a fatal
307 if ( count( $rawErrors ) == 1 ) {
308 $s = $this->getErrorMessage( $rawErrors[0], $lang );
309 if ( $shortContext ) {
310 $s = wfMessage( $shortContext, $s )->inLanguage( $lang );
311 } elseif ( $longContext ) {
312 $wrapper = new RawMessage( "* \$1\n" );
313 $wrapper->params( $s )->parse();
314 $s = wfMessage( $longContext, $wrapper )->inLanguage( $lang );
317 $msgs = $this->getErrorMessageArray( $rawErrors, $lang );
318 $msgCount = count( $msgs );
320 $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
321 $s->params( $msgs )->parse();
323 if ( $longContext ) {
324 $s = wfMessage( $longContext, $s )->inLanguage( $lang );
325 } elseif ( $shortContext ) {
326 $wrapper = new RawMessage( "\n\$1\n", [ $s ] );
328 $s = wfMessage( $shortContext, $wrapper )->inLanguage( $lang );
336 * Return the message for a single error.
338 * @param mixed $error With an array & two values keyed by
339 * 'message' and 'params', use those keys-value pairs.
340 * Otherwise, if its an array, just use the first value as the
341 * message and the remaining items as the params.
342 * @param string|Language $lang Language to use for processing messages
345 protected function getErrorMessage( $error, $lang = null ) {
346 if ( is_array( $error ) ) {
347 if ( isset( $error['message'] ) && $error['message'] instanceof Message
) {
348 $msg = $error['message'];
349 } elseif ( isset( $error['message'] ) && isset( $error['params'] ) ) {
350 $msg = wfMessage( $error['message'],
351 array_map( 'wfEscapeWikiText', $this->cleanParams( $error['params'] ) ) );
353 $msgName = array_shift( $error );
354 $msg = wfMessage( $msgName,
355 array_map( 'wfEscapeWikiText', $this->cleanParams( $error ) ) );
358 $msg = wfMessage( $error );
361 $msg->inLanguage( $this->languageFromParam( $lang ) );
366 * Get the error message as HTML. This is done by parsing the wikitext error
368 * @param string $shortContext A short enclosing context message name, to
369 * be used when there is a single error
370 * @param string $longContext A long enclosing context message name, for a list
371 * @param string|Language $lang Language to use for processing messages
374 public function getHTML( $shortContext = false, $longContext = false, $lang = null ) {
375 $lang = $this->languageFromParam( $lang );
376 $text = $this->getWikiText( $shortContext, $longContext, $lang );
377 $out = MessageCache
::singleton()->parse( $text, null, true, true, $lang );
378 return $out instanceof ParserOutput ?
$out->getText() : $out;
382 * Return an array with a Message object for each error.
383 * @param array $errors
384 * @param string|Language $lang Language to use for processing messages
387 protected function getErrorMessageArray( $errors, $lang = null ) {
388 $lang = $this->languageFromParam( $lang );
389 return array_map( function ( $e ) use ( $lang ) {
390 return $this->getErrorMessage( $e, $lang );
395 * Merge another status object into this one
397 * @param Status $other Other Status object
398 * @param bool $overwriteValue Whether to override the "value" member
400 public function merge( $other, $overwriteValue = false ) {
401 $this->sv
->merge( $other->sv
, $overwriteValue );
405 * Get the list of errors (but not warnings)
407 * @return array A list in which each entry is an array with a message key as its first element.
408 * The remaining array elements are the message parameters.
409 * @deprecated since 1.25
411 public function getErrorsArray() {
412 return $this->getStatusArray( 'error' );
416 * Get the list of warnings (but not errors)
418 * @return array A list in which each entry is an array with a message key as its first element.
419 * The remaining array elements are the message parameters.
420 * @deprecated since 1.25
422 public function getWarningsArray() {
423 return $this->getStatusArray( 'warning' );
427 * Returns a list of status messages of the given type (or all if false)
429 * @note: this handles RawMessage poorly
431 * @param string|bool $type
434 protected function getStatusArray( $type = false ) {
437 foreach ( $this->sv
->getErrors() as $error ) {
438 if ( $type === false ||
$error['type'] === $type ) {
439 if ( $error['message'] instanceof MessageSpecifier
) {
440 $result[] = array_merge(
441 [ $error['message']->getKey() ],
442 $error['message']->getParams()
444 } elseif ( $error['params'] ) {
445 $result[] = array_merge( [ $error['message'] ], $error['params'] );
447 $result[] = [ $error['message'] ];
456 * Returns a list of status messages of the given type, with message and
457 * params left untouched, like a sane version of getStatusArray
459 * Each entry is a map of:
460 * - message: string message key or MessageSpecifier
461 * - params: array list of parameters
463 * @param string $type
466 public function getErrorsByType( $type ) {
467 return $this->sv
->getErrorsByType( $type );
471 * Returns true if the specified message is present as a warning or error
473 * @param string|Message $message Message key or object to search for
477 public function hasMessage( $message ) {
478 return $this->sv
->hasMessage( $message );
482 * If the specified source message exists, replace it with the specified
483 * destination message, but keep the same parameters as in the original error.
485 * Note, due to the lack of tools for comparing Message objects, this
486 * function will not work when using a Message object as the search parameter.
488 * @param Message|string $source Message key or object to search for
489 * @param Message|string $dest Replacement message key or object
490 * @return bool Return true if the replacement was done, false otherwise.
492 public function replaceMessage( $source, $dest ) {
493 return $this->sv
->replaceMessage( $source, $dest );
499 public function getValue() {
500 return $this->sv
->getValue();
504 * Backwards compatibility logic
506 * @param string $name
508 function __get( $name ) {
509 if ( $name === 'ok' ) {
510 return $this->sv
->isOK();
511 } elseif ( $name === 'errors' ) {
512 return $this->sv
->getErrors();
514 throw new Exception( "Cannot get '$name' property." );
518 * Backwards compatibility logic
520 * @param string $name
521 * @param mixed $value
523 function __set( $name, $value ) {
524 if ( $name === 'ok' ) {
525 $this->sv
->setOK( $value );
526 } elseif ( !property_exists( $this, $name ) ) {
527 // Caller is using undeclared ad-hoc properties
528 $this->$name = $value;
530 throw new Exception( "Cannot set '$name' property." );
537 public function __toString() {
538 return $this->sv
->__toString();
542 * Don't save the callback when serializing, because Closures can't be
543 * serialized and we're going to clear it in __wakeup anyway.
546 $keys = array_keys( get_object_vars( $this ) );
547 return array_diff( $keys, [ 'cleanCallback' ] );
551 * Sanitize the callback parameter on wakeup, to avoid arbitrary execution.
553 function __wakeup() {
554 $this->cleanCallback
= false;