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 whether the operation completed and didn't have any error or
124 public function isGood() {
125 return $this->sv
->isGood();
129 * Returns whether the operation completed
133 public function isOK() {
134 return $this->sv
->isOK();
140 * @param string|Message $message Message name or object
142 public function warning( $message /*, parameters... */ ) {
143 call_user_func_array( [ $this->sv
, 'warning' ], func_get_args() );
147 * Add an error, do not set fatal flag
148 * This can be used for non-fatal errors
150 * @param string|Message $message Message name or object
152 public function error( $message /*, parameters... */ ) {
153 call_user_func_array( [ $this->sv
, 'error' ], func_get_args() );
157 * Add an error and set OK to false, indicating that the operation
158 * as a whole was fatal
160 * @param string|Message $message Message name or object
162 public function fatal( $message /*, parameters... */ ) {
163 call_user_func_array( [ $this->sv
, 'fatal' ], func_get_args() );
167 * @param array $params
170 protected function cleanParams( array $params ) {
171 if ( !$this->cleanCallback
) {
175 foreach ( $params as $i => $param ) {
176 $cleanParams[$i] = call_user_func( $this->cleanCallback
, $param );
182 * @param string|Language|null $lang Language to use for processing
183 * messages, or null to default to the user language.
186 protected function languageFromParam( $lang ) {
189 if ( $lang === null ) {
190 // @todo: Use RequestContext::getMain()->getLanguage() instead
192 } elseif ( $lang instanceof Language ||
$lang instanceof StubUserLang
) {
195 return Language
::factory( $lang );
200 * Get the error list as a wikitext formatted list
202 * @param string|bool $shortContext A short enclosing context message name, to
203 * be used when there is a single error
204 * @param string|bool $longContext A long enclosing context message name, for a list
205 * @param string|Language $lang Language to use for processing messages
208 public function getWikiText( $shortContext = false, $longContext = false, $lang = null ) {
209 $lang = $this->languageFromParam( $lang );
211 $rawErrors = $this->sv
->getErrors();
212 if ( count( $rawErrors ) == 0 ) {
213 if ( $this->sv
->isOK() ) {
214 $this->sv
->fatal( 'internalerror_info',
215 __METHOD__
. " called for a good result, this is incorrect\n" );
217 $this->sv
->fatal( 'internalerror_info',
218 __METHOD__
. ": Invalid result object: no error text but not OK\n" );
220 $rawErrors = $this->sv
->getErrors(); // just added a fatal
222 if ( count( $rawErrors ) == 1 ) {
223 $s = $this->getErrorMessage( $rawErrors[0], $lang )->plain();
224 if ( $shortContext ) {
225 $s = wfMessage( $shortContext, $s )->inLanguage( $lang )->plain();
226 } elseif ( $longContext ) {
227 $s = wfMessage( $longContext, "* $s\n" )->inLanguage( $lang )->plain();
230 $errors = $this->getErrorMessageArray( $rawErrors, $lang );
231 foreach ( $errors as &$error ) {
232 $error = $error->plain();
234 $s = '* ' . implode( "\n* ", $errors ) . "\n";
235 if ( $longContext ) {
236 $s = wfMessage( $longContext, $s )->inLanguage( $lang )->plain();
237 } elseif ( $shortContext ) {
238 $s = wfMessage( $shortContext, "\n$s\n" )->inLanguage( $lang )->plain();
245 * Get the error list as a Message object
247 * @param string|string[] $shortContext A short enclosing context message name (or an array of
248 * message names), to be used when there is a single error.
249 * @param string|string[] $longContext A long enclosing context message name (or an array of
250 * message names), for a list.
251 * @param string|Language $lang Language to use for processing messages
254 public function getMessage( $shortContext = false, $longContext = false, $lang = null ) {
255 $lang = $this->languageFromParam( $lang );
257 $rawErrors = $this->sv
->getErrors();
258 if ( count( $rawErrors ) == 0 ) {
259 if ( $this->sv
->isOK() ) {
260 $this->sv
->fatal( 'internalerror_info',
261 __METHOD__
. " called for a good result, this is incorrect\n" );
263 $this->sv
->fatal( 'internalerror_info',
264 __METHOD__
. ": Invalid result object: no error text but not OK\n" );
266 $rawErrors = $this->sv
->getErrors(); // just added a fatal
268 if ( count( $rawErrors ) == 1 ) {
269 $s = $this->getErrorMessage( $rawErrors[0], $lang );
270 if ( $shortContext ) {
271 $s = wfMessage( $shortContext, $s )->inLanguage( $lang );
272 } elseif ( $longContext ) {
273 $wrapper = new RawMessage( "* \$1\n" );
274 $wrapper->params( $s )->parse();
275 $s = wfMessage( $longContext, $wrapper )->inLanguage( $lang );
278 $msgs = $this->getErrorMessageArray( $rawErrors, $lang );
279 $msgCount = count( $msgs );
281 if ( $shortContext ) {
285 $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
286 $s->params( $msgs )->parse();
288 if ( $longContext ) {
289 $s = wfMessage( $longContext, $s )->inLanguage( $lang );
290 } elseif ( $shortContext ) {
291 $wrapper = new RawMessage( "\n\$1\n", [ $s ] );
293 $s = wfMessage( $shortContext, $wrapper )->inLanguage( $lang );
301 * Return the message for a single error.
302 * @param mixed $error With an array & two values keyed by
303 * 'message' and 'params', use those keys-value pairs.
304 * Otherwise, if its an array, just use the first value as the
305 * message and the remaining items as the params.
306 * @param string|Language $lang Language to use for processing messages
309 protected function getErrorMessage( $error, $lang = null ) {
310 if ( is_array( $error ) ) {
311 if ( isset( $error['message'] ) && $error['message'] instanceof Message
) {
312 $msg = $error['message'];
313 } elseif ( isset( $error['message'] ) && isset( $error['params'] ) ) {
314 $msg = wfMessage( $error['message'],
315 array_map( 'wfEscapeWikiText', $this->cleanParams( $error['params'] ) ) );
317 $msgName = array_shift( $error );
318 $msg = wfMessage( $msgName,
319 array_map( 'wfEscapeWikiText', $this->cleanParams( $error ) ) );
322 $msg = wfMessage( $error );
325 $msg->inLanguage( $this->languageFromParam( $lang ) );
330 * Get the error message as HTML. This is done by parsing the wikitext error
332 * @param string $shortContext A short enclosing context message name, to
333 * be used when there is a single error
334 * @param string $longContext A long enclosing context message name, for a list
335 * @param string|Language $lang Language to use for processing messages
338 public function getHTML( $shortContext = false, $longContext = false, $lang = null ) {
339 $lang = $this->languageFromParam( $lang );
340 $text = $this->getWikiText( $shortContext, $longContext, $lang );
341 $out = MessageCache
::singleton()->parse( $text, null, true, true, $lang );
342 return $out instanceof ParserOutput ?
$out->getText() : $out;
346 * Return an array with a Message object for each error.
347 * @param array $errors
348 * @param string|Language $lang Language to use for processing messages
351 protected function getErrorMessageArray( $errors, $lang = null ) {
352 $lang = $this->languageFromParam( $lang );
353 return array_map( function ( $e ) use ( $lang ) {
354 return $this->getErrorMessage( $e, $lang );
359 * Merge another status object into this one
361 * @param Status $other Other Status object
362 * @param bool $overwriteValue Whether to override the "value" member
364 public function merge( $other, $overwriteValue = false ) {
365 $this->sv
->merge( $other->sv
, $overwriteValue );
369 * Get the list of errors (but not warnings)
371 * @return array A list in which each entry is an array with a message key as its first element.
372 * The remaining array elements are the message parameters.
375 public function getErrorsArray() {
376 return $this->getStatusArray( 'error' );
380 * Get the list of warnings (but not errors)
382 * @return array A list in which each entry is an array with a message key as its first element.
383 * The remaining array elements are the message parameters.
386 public function getWarningsArray() {
387 return $this->getStatusArray( 'warning' );
391 * Returns a list of status messages of the given type (or all if false)
393 * @note: this handles RawMessage poorly
395 * @param string|bool $type
398 protected function getStatusArray( $type = false ) {
401 foreach ( $this->sv
->getErrors() as $error ) {
402 if ( $type === false ||
$error['type'] === $type ) {
403 if ( $error['message'] instanceof MessageSpecifier
) {
404 $result[] = array_merge(
405 [ $error['message']->getKey() ],
406 $error['message']->getParams()
408 } elseif ( $error['params'] ) {
409 $result[] = array_merge( [ $error['message'] ], $error['params'] );
411 $result[] = [ $error['message'] ];
420 * Returns a list of status messages of the given type, with message and
421 * params left untouched, like a sane version of getStatusArray
423 * @param string $type
427 public function getErrorsByType( $type ) {
428 return $this->sv
->getErrorsByType( $type );
432 * Returns true if the specified message is present as a warning or error
434 * @param string|Message $message Message key or object to search for
438 public function hasMessage( $message ) {
439 return $this->sv
->hasMessage( $message );
443 * If the specified source message exists, replace it with the specified
444 * destination message, but keep the same parameters as in the original error.
446 * Note, due to the lack of tools for comparing Message objects, this
447 * function will not work when using a Message object as the search parameter.
449 * @param Message|string $source Message key or object to search for
450 * @param Message|string $dest Replacement message key or object
451 * @return bool Return true if the replacement was done, false otherwise.
453 public function replaceMessage( $source, $dest ) {
454 return $this->sv
->replaceMessage( $source, $dest );
460 public function getValue() {
461 return $this->sv
->getValue();
465 * Backwards compatibility logic
467 * @param string $name
469 function __get( $name ) {
470 if ( $name === 'ok' ) {
471 return $this->sv
->isOK();
472 } elseif ( $name === 'errors' ) {
473 return $this->sv
->getErrors();
475 throw new Exception( "Cannot get '$name' property." );
479 * Backwards compatibility logic
481 * @param string $name
482 * @param mixed $value
484 function __set( $name, $value ) {
485 if ( $name === 'ok' ) {
486 $this->sv
->setOK( $value );
487 } elseif ( !property_exists( $this, $name ) ) {
488 // Caller is using undeclared ad-hoc properties
489 $this->$name = $value;
491 throw new Exception( "Cannot set '$name' property." );
498 public function __toString() {
499 return $this->sv
->__toString();
503 * Don't save the callback when serializing, because Closures can't be
504 * serialized and we're going to clear it in __wakeup anyway.
507 $keys = array_keys( get_object_vars( $this ) );
508 return array_diff( $keys, [ 'cleanCallback' ] );
512 * Sanitize the callback parameter on wakeup, to avoid arbitrary execution.
514 function __wakeup() {
515 $this->cleanCallback
= false;