In MediaWikiTestCase::stashMwGlobals(), prefer shallow copies
[mediawiki.git] / includes / Status.php
blobf8370e448879de561605de097ec4f7ac958d6be9
1 <?php
2 /**
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
20 * @file
23 /**
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.
40 class Status {
41 /** @var StatusValue */
42 protected $sv;
44 /** @var mixed */
45 public $value;
46 /** @var array Map of (key => bool) to indicate success of each part of batch operations */
47 public $success = [];
48 /** @var int Counter for batch operations */
49 public $successCount = 0;
50 /** @var int Counter for batch operations */
51 public $failCount = 0;
53 /** @var callable */
54 public $cleanCallback = false;
56 /**
57 * @param StatusValue $sv [optional]
59 public function __construct( StatusValue $sv = null ) {
60 $this->sv = ( $sv === null ) ? new StatusValue() : $sv;
61 // B/C field aliases
62 $this->value =& $this->sv->value;
63 $this->successCount =& $this->sv->successCount;
64 $this->failCount =& $this->sv->failCount;
65 $this->success =& $this->sv->success;
68 /**
69 * Succinct helper method to wrap a StatusValue
71 * This is is useful when formatting StatusValue objects:
72 * @code
73 * $this->getOutput()->addHtml( Status::wrap( $sv )->getHTML() );
74 * @endcode
76 * @param StatusValue|Status $sv
77 * @return Status
79 public static function wrap( $sv ) {
80 return $sv instanceof Status ? $sv : new self( $sv );
83 /**
84 * Factory function for fatal errors
86 * @param string|Message $message Message name or object
87 * @return Status
89 public static function newFatal( $message /*, parameters...*/ ) {
90 return new self( call_user_func_array(
91 [ 'StatusValue', 'newFatal' ], func_get_args()
92 ) );
95 /**
96 * Factory function for good results
98 * @param mixed $value
99 * @return Status
101 public static function newGood( $value = null ) {
102 $sv = new StatusValue();
103 $sv->value = $value;
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() {
123 return $this->sv;
127 * Returns whether the operation completed and didn't have any error or
128 * warnings
130 * @return bool
132 public function isGood() {
133 return $this->sv->isGood();
137 * Returns whether the operation completed
139 * @return bool
141 public function isOK() {
142 return $this->sv->isOK();
146 * Add a new warning
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
176 * @return array
178 protected function cleanParams( array $params ) {
179 if ( !$this->cleanCallback ) {
180 return $params;
182 $cleanParams = [];
183 foreach ( $params as $i => $param ) {
184 $cleanParams[$i] = call_user_func( $this->cleanCallback, $param );
186 return $cleanParams;
190 * @param string|Language|null $lang Language to use for processing
191 * messages, or null to default to the user language.
192 * @return Language
194 protected function languageFromParam( $lang ) {
195 global $wgLang;
197 if ( $lang === null ) {
198 // @todo: Use RequestContext::getMain()->getLanguage() instead
199 return $wgLang;
200 } elseif ( $lang instanceof Language || $lang instanceof StubUserLang ) {
201 return $lang;
202 } else {
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
214 * @return string
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" );
224 } else {
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();
237 } else {
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();
249 return $s;
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
260 * @return Message
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" );
270 } else {
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 );
285 } else {
286 $msgs = $this->getErrorMessageArray( $rawErrors, $lang );
287 $msgCount = count( $msgs );
289 if ( $shortContext ) {
290 $msgCount++;
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 ] );
300 $wrapper->parse();
301 $s = wfMessage( $shortContext, $wrapper )->inLanguage( $lang );
305 return $s;
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
315 * @return Message
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'] ) ) );
324 } else {
325 $msgName = array_shift( $error );
326 $msg = wfMessage( $msgName,
327 array_map( 'wfEscapeWikiText', $this->cleanParams( $error ) ) );
329 } else {
330 $msg = wfMessage( $error );
333 $msg->inLanguage( $this->languageFromParam( $lang ) );
334 return $msg;
338 * Get the error message as HTML. This is done by parsing the wikitext error
339 * message.
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
344 * @return string
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
357 * @return Message[]
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 );
363 }, $errors );
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.
381 * @deprecated 1.25
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.
392 * @deprecated 1.25
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
404 * @return array
406 protected function getStatusArray( $type = false ) {
407 $result = [];
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'] );
418 } else {
419 $result[] = [ $error['message'] ];
424 return $result;
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
436 * @return array
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
447 * @return bool
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 );
469 * @return mixed
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;
501 } else {
502 throw new Exception( "Cannot set '$name' property." );
507 * @return string
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.
517 function __sleep() {
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;