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 * Change operation result
111 * @param bool $ok Whether the operation completed
112 * @param mixed $value
114 public function setResult( $ok, $value = null ) {
115 $this->sv
->setResult( $ok, $value );
119 * Returns the wrapped StatusValue object
120 * @return StatusValue
122 public function getStatusValue() {
127 * Returns whether the operation completed and didn't have any error or
132 public function isGood() {
133 return $this->sv
->isGood();
137 * Returns whether the operation completed
141 public function isOK() {
142 return $this->sv
->isOK();
148 * @param string|Message $message Message name or object
150 public function warning( $message /*, parameters... */ ) {
151 call_user_func_array( [ $this->sv
, 'warning' ], func_get_args() );
155 * Add an error, do not set fatal flag
156 * This can be used for non-fatal errors
158 * @param string|Message $message Message name or object
160 public function error( $message /*, parameters... */ ) {
161 call_user_func_array( [ $this->sv
, 'error' ], func_get_args() );
165 * Add an error and set OK to false, indicating that the operation
166 * as a whole was fatal
168 * @param string|Message $message Message name or object
170 public function fatal( $message /*, parameters... */ ) {
171 call_user_func_array( [ $this->sv
, 'fatal' ], func_get_args() );
175 * @param array $params
178 protected function cleanParams( array $params ) {
179 if ( !$this->cleanCallback
) {
183 foreach ( $params as $i => $param ) {
184 $cleanParams[$i] = call_user_func( $this->cleanCallback
, $param );
190 * @param string|Language|null $lang Language to use for processing
191 * messages, or null to default to the user language.
194 protected function languageFromParam( $lang ) {
197 if ( $lang === null ) {
198 // @todo: Use RequestContext::getMain()->getLanguage() instead
200 } elseif ( $lang instanceof Language ||
$lang instanceof StubUserLang
) {
203 return Language
::factory( $lang );
208 * Get the error list as a wikitext formatted list
210 * @param string|bool $shortContext A short enclosing context message name, to
211 * be used when there is a single error
212 * @param string|bool $longContext A long enclosing context message name, for a list
213 * @param string|Language $lang Language to use for processing messages
216 public function getWikiText( $shortContext = false, $longContext = false, $lang = null ) {
217 $lang = $this->languageFromParam( $lang );
219 $rawErrors = $this->sv
->getErrors();
220 if ( count( $rawErrors ) == 0 ) {
221 if ( $this->sv
->isOK() ) {
222 $this->sv
->fatal( 'internalerror_info',
223 __METHOD__
. " called for a good result, this is incorrect\n" );
225 $this->sv
->fatal( 'internalerror_info',
226 __METHOD__
. ": Invalid result object: no error text but not OK\n" );
228 $rawErrors = $this->sv
->getErrors(); // just added a fatal
230 if ( count( $rawErrors ) == 1 ) {
231 $s = $this->getErrorMessage( $rawErrors[0], $lang )->plain();
232 if ( $shortContext ) {
233 $s = wfMessage( $shortContext, $s )->inLanguage( $lang )->plain();
234 } elseif ( $longContext ) {
235 $s = wfMessage( $longContext, "* $s\n" )->inLanguage( $lang )->plain();
238 $errors = $this->getErrorMessageArray( $rawErrors, $lang );
239 foreach ( $errors as &$error ) {
240 $error = $error->plain();
242 $s = '* ' . implode( "\n* ", $errors ) . "\n";
243 if ( $longContext ) {
244 $s = wfMessage( $longContext, $s )->inLanguage( $lang )->plain();
245 } elseif ( $shortContext ) {
246 $s = wfMessage( $shortContext, "\n$s\n" )->inLanguage( $lang )->plain();
253 * Get the error list as a Message object
255 * @param string|string[] $shortContext A short enclosing context message name (or an array of
256 * message names), to be used when there is a single error.
257 * @param string|string[] $longContext A long enclosing context message name (or an array of
258 * message names), for a list.
259 * @param string|Language $lang Language to use for processing messages
262 public function getMessage( $shortContext = false, $longContext = false, $lang = null ) {
263 $lang = $this->languageFromParam( $lang );
265 $rawErrors = $this->sv
->getErrors();
266 if ( count( $rawErrors ) == 0 ) {
267 if ( $this->sv
->isOK() ) {
268 $this->sv
->fatal( 'internalerror_info',
269 __METHOD__
. " called for a good result, this is incorrect\n" );
271 $this->sv
->fatal( 'internalerror_info',
272 __METHOD__
. ": Invalid result object: no error text but not OK\n" );
274 $rawErrors = $this->sv
->getErrors(); // just added a fatal
276 if ( count( $rawErrors ) == 1 ) {
277 $s = $this->getErrorMessage( $rawErrors[0], $lang );
278 if ( $shortContext ) {
279 $s = wfMessage( $shortContext, $s )->inLanguage( $lang );
280 } elseif ( $longContext ) {
281 $wrapper = new RawMessage( "* \$1\n" );
282 $wrapper->params( $s )->parse();
283 $s = wfMessage( $longContext, $wrapper )->inLanguage( $lang );
286 $msgs = $this->getErrorMessageArray( $rawErrors, $lang );
287 $msgCount = count( $msgs );
289 if ( $shortContext ) {
293 $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
294 $s->params( $msgs )->parse();
296 if ( $longContext ) {
297 $s = wfMessage( $longContext, $s )->inLanguage( $lang );
298 } elseif ( $shortContext ) {
299 $wrapper = new RawMessage( "\n\$1\n", [ $s ] );
301 $s = wfMessage( $shortContext, $wrapper )->inLanguage( $lang );
309 * Return the message for a single error.
310 * @param mixed $error With an array & two values keyed by
311 * 'message' and 'params', use those keys-value pairs.
312 * Otherwise, if its an array, just use the first value as the
313 * message and the remaining items as the params.
314 * @param string|Language $lang Language to use for processing messages
317 protected function getErrorMessage( $error, $lang = null ) {
318 if ( is_array( $error ) ) {
319 if ( isset( $error['message'] ) && $error['message'] instanceof Message
) {
320 $msg = $error['message'];
321 } elseif ( isset( $error['message'] ) && isset( $error['params'] ) ) {
322 $msg = wfMessage( $error['message'],
323 array_map( 'wfEscapeWikiText', $this->cleanParams( $error['params'] ) ) );
325 $msgName = array_shift( $error );
326 $msg = wfMessage( $msgName,
327 array_map( 'wfEscapeWikiText', $this->cleanParams( $error ) ) );
330 $msg = wfMessage( $error );
333 $msg->inLanguage( $this->languageFromParam( $lang ) );
338 * Get the error message as HTML. This is done by parsing the wikitext error
340 * @param string $shortContext A short enclosing context message name, to
341 * be used when there is a single error
342 * @param string $longContext A long enclosing context message name, for a list
343 * @param string|Language $lang Language to use for processing messages
346 public function getHTML( $shortContext = false, $longContext = false, $lang = null ) {
347 $lang = $this->languageFromParam( $lang );
348 $text = $this->getWikiText( $shortContext, $longContext, $lang );
349 $out = MessageCache
::singleton()->parse( $text, null, true, true, $lang );
350 return $out instanceof ParserOutput ?
$out->getText() : $out;
354 * Return an array with a Message object for each error.
355 * @param array $errors
356 * @param string|Language $lang Language to use for processing messages
359 protected function getErrorMessageArray( $errors, $lang = null ) {
360 $lang = $this->languageFromParam( $lang );
361 return array_map( function ( $e ) use ( $lang ) {
362 return $this->getErrorMessage( $e, $lang );
367 * Merge another status object into this one
369 * @param Status $other Other Status object
370 * @param bool $overwriteValue Whether to override the "value" member
372 public function merge( $other, $overwriteValue = false ) {
373 $this->sv
->merge( $other->sv
, $overwriteValue );
377 * Get the list of errors (but not warnings)
379 * @return array A list in which each entry is an array with a message key as its first element.
380 * The remaining array elements are the message parameters.
383 public function getErrorsArray() {
384 return $this->getStatusArray( 'error' );
388 * Get the list of warnings (but not errors)
390 * @return array A list in which each entry is an array with a message key as its first element.
391 * The remaining array elements are the message parameters.
394 public function getWarningsArray() {
395 return $this->getStatusArray( 'warning' );
399 * Returns a list of status messages of the given type (or all if false)
401 * @note: this handles RawMessage poorly
403 * @param string|bool $type
406 protected function getStatusArray( $type = false ) {
409 foreach ( $this->sv
->getErrors() as $error ) {
410 if ( $type === false ||
$error['type'] === $type ) {
411 if ( $error['message'] instanceof MessageSpecifier
) {
412 $result[] = array_merge(
413 [ $error['message']->getKey() ],
414 $error['message']->getParams()
416 } elseif ( $error['params'] ) {
417 $result[] = array_merge( [ $error['message'] ], $error['params'] );
419 $result[] = [ $error['message'] ];
428 * Returns a list of status messages of the given type, with message and
429 * params left untouched, like a sane version of getStatusArray
431 * Each entry is a map of:
432 * - message: string message key or MessageSpecifier
433 * - params: array list of parameters
435 * @param string $type
438 public function getErrorsByType( $type ) {
439 return $this->sv
->getErrorsByType( $type );
443 * Returns true if the specified message is present as a warning or error
445 * @param string|Message $message Message key or object to search for
449 public function hasMessage( $message ) {
450 return $this->sv
->hasMessage( $message );
454 * If the specified source message exists, replace it with the specified
455 * destination message, but keep the same parameters as in the original error.
457 * Note, due to the lack of tools for comparing Message objects, this
458 * function will not work when using a Message object as the search parameter.
460 * @param Message|string $source Message key or object to search for
461 * @param Message|string $dest Replacement message key or object
462 * @return bool Return true if the replacement was done, false otherwise.
464 public function replaceMessage( $source, $dest ) {
465 return $this->sv
->replaceMessage( $source, $dest );
471 public function getValue() {
472 return $this->sv
->getValue();
476 * Backwards compatibility logic
478 * @param string $name
480 function __get( $name ) {
481 if ( $name === 'ok' ) {
482 return $this->sv
->isOK();
483 } elseif ( $name === 'errors' ) {
484 return $this->sv
->getErrors();
486 throw new Exception( "Cannot get '$name' property." );
490 * Backwards compatibility logic
492 * @param string $name
493 * @param mixed $value
495 function __set( $name, $value ) {
496 if ( $name === 'ok' ) {
497 $this->sv
->setOK( $value );
498 } elseif ( !property_exists( $this, $name ) ) {
499 // Caller is using undeclared ad-hoc properties
500 $this->$name = $value;
502 throw new Exception( "Cannot set '$name' property." );
509 public function __toString() {
510 return $this->sv
->__toString();
514 * Don't save the callback when serializing, because Closures can't be
515 * serialized and we're going to clear it in __wakeup anyway.
518 $keys = array_keys( get_object_vars( $this ) );
519 return array_diff( $keys, [ 'cleanCallback' ] );
523 * Sanitize the callback parameter on wakeup, to avoid arbitrary execution.
525 function __wakeup() {
526 $this->cleanCallback
= false;