Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / Status.php
blobcd10258d5802bb329a4894857e20eacdf96466c4
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 = array();
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 * </code>
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 array( '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 whether the operation completed and didn't have any error or
120 * warnings
122 * @return bool
124 public function isGood() {
125 return $this->sv->isGood();
129 * Returns whether the operation completed
131 * @return bool
133 public function isOK() {
134 return $this->sv->isOK();
138 * Add a new warning
140 * @param string|Message $message Message name or object
142 public function warning( $message /*, parameters... */ ) {
143 call_user_func_array( 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( 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( array( $this->sv, 'fatal' ), func_get_args() );
167 * @param array $params
168 * @return array
170 protected function cleanParams( array $params ) {
171 if ( !$this->cleanCallback ) {
172 return $params;
174 $cleanParams = array();
175 foreach ( $params as $i => $param ) {
176 $cleanParams[$i] = call_user_func( $this->cleanCallback, $param );
178 return $cleanParams;
182 * Get the error list as a wikitext formatted list
184 * @param string|bool $shortContext A short enclosing context message name, to
185 * be used when there is a single error
186 * @param string|bool $longContext A long enclosing context message name, for a list
187 * @return string
189 public function getWikiText( $shortContext = false, $longContext = false ) {
190 $rawErrors = $this->sv->getErrors();
191 if ( count( $rawErrors ) == 0 ) {
192 if ( $this->sv->isOK() ) {
193 $this->sv->fatal( 'internalerror_info',
194 __METHOD__ . " called for a good result, this is incorrect\n" );
195 } else {
196 $this->sv->fatal( 'internalerror_info',
197 __METHOD__ . ": Invalid result object: no error text but not OK\n" );
199 $rawErrors = $this->sv->getErrors(); // just added a fatal
201 if ( count( $rawErrors ) == 1 ) {
202 $s = $this->getErrorMessage( $rawErrors[0] )->plain();
203 if ( $shortContext ) {
204 $s = wfMessage( $shortContext, $s )->plain();
205 } elseif ( $longContext ) {
206 $s = wfMessage( $longContext, "* $s\n" )->plain();
208 } else {
209 $errors = $this->getErrorMessageArray( $rawErrors );
210 foreach ( $errors as &$error ) {
211 $error = $error->plain();
213 $s = '* ' . implode( "\n* ", $errors ) . "\n";
214 if ( $longContext ) {
215 $s = wfMessage( $longContext, $s )->plain();
216 } elseif ( $shortContext ) {
217 $s = wfMessage( $shortContext, "\n$s\n" )->plain();
220 return $s;
224 * Get the error list as a Message object
226 * @param string|string[] $shortContext A short enclosing context message name (or an array of
227 * message names), to be used when there is a single error.
228 * @param string|string[] $longContext A long enclosing context message name (or an array of
229 * message names), for a list.
231 * @return Message
233 public function getMessage( $shortContext = false, $longContext = false ) {
234 $rawErrors = $this->sv->getErrors();
235 if ( count( $rawErrors ) == 0 ) {
236 if ( $this->sv->isOK() ) {
237 $this->sv->fatal( 'internalerror_info',
238 __METHOD__ . " called for a good result, this is incorrect\n" );
239 } else {
240 $this->sv->fatal( 'internalerror_info',
241 __METHOD__ . ": Invalid result object: no error text but not OK\n" );
243 $rawErrors = $this->sv->getErrors(); // just added a fatal
245 if ( count( $rawErrors ) == 1 ) {
246 $s = $this->getErrorMessage( $rawErrors[0] );
247 if ( $shortContext ) {
248 $s = wfMessage( $shortContext, $s );
249 } elseif ( $longContext ) {
250 $wrapper = new RawMessage( "* \$1\n" );
251 $wrapper->params( $s )->parse();
252 $s = wfMessage( $longContext, $wrapper );
254 } else {
255 $msgs = $this->getErrorMessageArray( $rawErrors );
256 $msgCount = count( $msgs );
258 if ( $shortContext ) {
259 $msgCount++;
262 $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
263 $s->params( $msgs )->parse();
265 if ( $longContext ) {
266 $s = wfMessage( $longContext, $s );
267 } elseif ( $shortContext ) {
268 $wrapper = new RawMessage( "\n\$1\n", $s );
269 $wrapper->parse();
270 $s = wfMessage( $shortContext, $wrapper );
274 return $s;
278 * Return the message for a single error.
279 * @param mixed $error With an array & two values keyed by
280 * 'message' and 'params', use those keys-value pairs.
281 * Otherwise, if its an array, just use the first value as the
282 * message and the remaining items as the params.
284 * @return string
286 protected function getErrorMessage( $error ) {
287 if ( is_array( $error ) ) {
288 if ( isset( $error['message'] ) && $error['message'] instanceof Message ) {
289 $msg = $error['message'];
290 } elseif ( isset( $error['message'] ) && isset( $error['params'] ) ) {
291 $msg = wfMessage( $error['message'],
292 array_map( 'wfEscapeWikiText', $this->cleanParams( $error['params'] ) ) );
293 } else {
294 $msgName = array_shift( $error );
295 $msg = wfMessage( $msgName,
296 array_map( 'wfEscapeWikiText', $this->cleanParams( $error ) ) );
298 } else {
299 $msg = wfMessage( $error );
301 return $msg;
305 * Get the error message as HTML. This is done by parsing the wikitext error
306 * message.
307 * @param string $shortContext A short enclosing context message name, to
308 * be used when there is a single error
309 * @param string $longContext A long enclosing context message name, for a list
310 * @return string
312 public function getHTML( $shortContext = false, $longContext = false ) {
313 $text = $this->getWikiText( $shortContext, $longContext );
314 $out = MessageCache::singleton()->parse( $text, null, true, true );
315 return $out instanceof ParserOutput ? $out->getText() : $out;
319 * Return an array with the wikitext for each item in the array.
320 * @param array $errors
321 * @return array
323 protected function getErrorMessageArray( $errors ) {
324 return array_map( array( $this, 'getErrorMessage' ), $errors );
328 * Merge another status object into this one
330 * @param Status $other Other Status object
331 * @param bool $overwriteValue Whether to override the "value" member
333 public function merge( $other, $overwriteValue = false ) {
334 $this->sv->merge( $other->sv, $overwriteValue );
338 * Get the list of errors (but not warnings)
340 * @return array A list in which each entry is an array with a message key as its first element.
341 * The remaining array elements are the message parameters.
342 * @deprecated 1.25
344 public function getErrorsArray() {
345 return $this->getStatusArray( 'error' );
349 * Get the list of warnings (but not errors)
351 * @return array A list in which each entry is an array with a message key as its first element.
352 * The remaining array elements are the message parameters.
353 * @deprecated 1.25
355 public function getWarningsArray() {
356 return $this->getStatusArray( 'warning' );
360 * Returns a list of status messages of the given type (or all if false)
362 * @note: this handles RawMessage poorly
364 * @param string $type
365 * @return array
367 protected function getStatusArray( $type = false ) {
368 $result = array();
370 foreach ( $this->sv->getErrors() as $error ) {
371 if ( $type === false || $error['type'] === $type ) {
372 if ( $error['message'] instanceof MessageSpecifier ) {
373 $result[] = array_merge(
374 array( $error['message']->getKey() ),
375 $error['message']->getParams()
377 } elseif ( $error['params'] ) {
378 $result[] = array_merge( array( $error['message'] ), $error['params'] );
379 } else {
380 $result[] = array( $error['message'] );
385 return $result;
389 * Returns a list of status messages of the given type, with message and
390 * params left untouched, like a sane version of getStatusArray
392 * @param string $type
394 * @return array
396 public function getErrorsByType( $type ) {
397 return $this->sv->getErrorsByType( $type );
401 * Returns true if the specified message is present as a warning or error
403 * @param string|Message $message Message key or object to search for
405 * @return bool
407 public function hasMessage( $message ) {
408 return $this->sv->hasMessage( $message );
412 * If the specified source message exists, replace it with the specified
413 * destination message, but keep the same parameters as in the original error.
415 * Note, due to the lack of tools for comparing Message objects, this
416 * function will not work when using a Message object as the search parameter.
418 * @param Message|string $source Message key or object to search for
419 * @param Message|string $dest Replacement message key or object
420 * @return bool Return true if the replacement was done, false otherwise.
422 public function replaceMessage( $source, $dest ) {
423 return $this->sv->replaceMessage( $source, $dest );
427 * @return mixed
429 public function getValue() {
430 return $this->sv->getValue();
434 * Backwards compatibility logic
436 * @param string $name
438 function __get( $name ) {
439 if ( $name === 'ok' ) {
440 return $this->sv->isOK();
441 } elseif ( $name === 'errors' ) {
442 return $this->sv->getErrors();
444 throw new Exception( "Cannot get '$name' property." );
448 * Backwards compatibility logic
450 * @param string $name
451 * @param mixed $value
453 function __set( $name, $value ) {
454 if ( $name === 'ok' ) {
455 $this->sv->setOK( $value );
456 } elseif ( !property_exists( $this, $name ) ) {
457 // Caller is using undeclared ad-hoc properties
458 $this->$name = $value;
459 } else {
460 throw new Exception( "Cannot set '$name' property." );
465 * @return string
467 public function __toString() {
468 return $this->sv->__toString();
472 * Don't save the callback when serializing, because Closures can't be
473 * serialized and we're going to clear it in __wakeup anyway.
475 function __sleep() {
476 $keys = array_keys( get_object_vars( $this ) );
477 return array_diff( $keys, array( 'cleanCallback' ) );
481 * Sanitize the callback parameter on wakeup, to avoid arbitrary execution.
483 function __wakeup() {
484 $this->cleanCallback = false;