Merge "Declare visibility for class properties of LocalisationCacheBulkLoad"
[mediawiki.git] / includes / api / ApiResult.php
blobe92202025ec8b9c99509356956ab7ec13d72279a
1 <?php
2 /**
5 * Created on Sep 4, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
24 * @file
27 /**
28 * This class represents the result of the API operations.
29 * It simply wraps a nested array() structure, adding some functions to simplify
30 * array's modifications. As various modules execute, they add different pieces
31 * of information to this result, structuring it as it will be given to the client.
33 * Each subarray may either be a dictionary - key-value pairs with unique keys,
34 * or lists, where the items are added using $data[] = $value notation.
36 * There are two special key values that change how XML output is generated:
37 * '_element' This key sets the tag name for the rest of the elements in the current array.
38 * It is only inserted if the formatter returned true for getNeedsRawData()
39 * '*' This key has special meaning only to the XML formatter, and is outputted as is
40 * for all others. In XML it becomes the content of the current element.
42 * @ingroup API
44 class ApiResult extends ApiBase {
46 /**
47 * override existing value in addValue() and setElement()
48 * @since 1.21
50 const OVERRIDE = 1;
52 /**
53 * For addValue() and setElement(), if the value does not exist, add it as the first element.
54 * In case the new value has no name (numerical index), all indexes will be renumbered.
55 * @since 1.21
57 const ADD_ON_TOP = 2;
59 private $mData, $mIsRawMode, $mSize, $mCheckingSize;
61 /**
62 * Constructor
63 * @param $main ApiMain object
65 public function __construct( $main ) {
66 parent::__construct( $main, 'result' );
67 $this->mIsRawMode = false;
68 $this->mCheckingSize = true;
69 $this->reset();
72 /**
73 * Clear the current result data.
75 public function reset() {
76 $this->mData = array();
77 $this->mSize = 0;
80 /**
81 * Call this function when special elements such as '_element'
82 * are needed by the formatter, for example in XML printing.
84 public function setRawMode() {
85 $this->mIsRawMode = true;
88 /**
89 * Returns true whether the formatter requested raw data.
90 * @return bool
92 public function getIsRawMode() {
93 return $this->mIsRawMode;
96 /**
97 * Get the result's internal data array (read-only)
98 * @return array
100 public function getData() {
101 return $this->mData;
105 * Get the 'real' size of a result item. This means the strlen() of the item,
106 * or the sum of the strlen()s of the elements if the item is an array.
107 * @param $value mixed
108 * @return int
110 public static function size( $value ) {
111 $s = 0;
112 if ( is_array( $value ) ) {
113 foreach ( $value as $v ) {
114 $s += self::size( $v );
116 } elseif ( !is_object( $value ) ) {
117 // Objects can't always be cast to string
118 $s = strlen( $value );
121 return $s;
125 * Get the size of the result, i.e. the amount of bytes in it
126 * @return int
128 public function getSize() {
129 return $this->mSize;
133 * Disable size checking in addValue(). Don't use this unless you
134 * REALLY know what you're doing. Values added while size checking
135 * was disabled will not be counted (ever)
137 public function disableSizeCheck() {
138 $this->mCheckingSize = false;
142 * Re-enable size checking in addValue()
144 public function enableSizeCheck() {
145 $this->mCheckingSize = true;
149 * Add an output value to the array by name.
150 * Verifies that value with the same name has not been added before.
151 * @param array $arr to add $value to
152 * @param string $name Index of $arr to add $value at
153 * @param $value mixed
154 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
155 * This parameter used to be boolean, and the value of OVERRIDE=1 was
156 * specifically chosen so that it would be backwards compatible with the
157 * new method signature.
159 * @since 1.21 int $flags replaced boolean $override
161 public static function setElement( &$arr, $name, $value, $flags = 0 ) {
162 if ( $arr === null || $name === null || $value === null
163 || !is_array( $arr ) || is_array( $name )
165 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
168 $exists = isset( $arr[$name] );
169 if ( !$exists || ( $flags & ApiResult::OVERRIDE ) ) {
170 if ( !$exists && ( $flags & ApiResult::ADD_ON_TOP ) ) {
171 $arr = array( $name => $value ) + $arr;
172 } else {
173 $arr[$name] = $value;
175 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
176 $merged = array_intersect_key( $arr[$name], $value );
177 if ( !count( $merged ) ) {
178 $arr[$name] += $value;
179 } else {
180 ApiBase::dieDebug( __METHOD__, "Attempting to merge element $name" );
182 } else {
183 ApiBase::dieDebug(
184 __METHOD__,
185 "Attempting to add element $name=$value, existing value is {$arr[$name]}"
191 * Adds a content element to an array.
192 * Use this function instead of hardcoding the '*' element.
193 * @param array $arr to add the content element to
194 * @param $value Mixed
195 * @param string $subElemName when present, content element is created
196 * as a sub item of $arr. Use this parameter to create elements in
197 * format "<elem>text</elem>" without attributes.
199 public static function setContent( &$arr, $value, $subElemName = null ) {
200 if ( is_array( $value ) ) {
201 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
203 if ( is_null( $subElemName ) ) {
204 ApiResult::setElement( $arr, '*', $value );
205 } else {
206 if ( !isset( $arr[$subElemName] ) ) {
207 $arr[$subElemName] = array();
209 ApiResult::setElement( $arr[$subElemName], '*', $value );
214 * In case the array contains indexed values (in addition to named),
215 * give all indexed values the given tag name. This function MUST be
216 * called on every array that has numerical indexes.
217 * @param $arr array
218 * @param string $tag Tag name
220 public function setIndexedTagName( &$arr, $tag ) {
221 // In raw mode, add the '_element', otherwise just ignore
222 if ( !$this->getIsRawMode() ) {
223 return;
225 if ( $arr === null || $tag === null || !is_array( $arr ) || is_array( $tag ) ) {
226 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
228 // Do not use setElement() as it is ok to call this more than once
229 $arr['_element'] = $tag;
233 * Calls setIndexedTagName() on each sub-array of $arr
234 * @param $arr array
235 * @param string $tag Tag name
237 public function setIndexedTagName_recursive( &$arr, $tag ) {
238 if ( !is_array( $arr ) ) {
239 return;
241 foreach ( $arr as &$a ) {
242 if ( !is_array( $a ) ) {
243 continue;
245 $this->setIndexedTagName( $a, $tag );
246 $this->setIndexedTagName_recursive( $a, $tag );
251 * Calls setIndexedTagName() on an array already in the result.
252 * Don't specify a path to a value that's not in the result, or
253 * you'll get nasty errors.
254 * @param array $path Path to the array, like addValue()'s $path
255 * @param $tag string
257 public function setIndexedTagName_internal( $path, $tag ) {
258 $data = &$this->mData;
259 foreach ( (array)$path as $p ) {
260 if ( !isset( $data[$p] ) ) {
261 $data[$p] = array();
263 $data = &$data[$p];
265 if ( is_null( $data ) ) {
266 return;
268 $this->setIndexedTagName( $data, $tag );
272 * Add value to the output data at the given path.
273 * Path can be an indexed array, each element specifying the branch at which to add the new
274 * value. Setting $path to array('a','b','c') is equivalent to data['a']['b']['c'] = $value.
275 * If $path is null, the value will be inserted at the data root.
276 * If $name is empty, the $value is added as a next list element data[] = $value.
278 * @param $path array|string|null
279 * @param $name string
280 * @param $value mixed
281 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP. This
282 * parameter used to be boolean, and the value of OVERRIDE=1 was specifically
283 * chosen so that it would be backwards compatible with the new method
284 * signature.
285 * @return bool True if $value fits in the result, false if not
287 * @since 1.21 int $flags replaced boolean $override
289 public function addValue( $path, $name, $value, $flags = 0 ) {
290 global $wgAPIMaxResultSize;
292 $data = &$this->mData;
293 if ( $this->mCheckingSize ) {
294 $newsize = $this->mSize + self::size( $value );
295 if ( $newsize > $wgAPIMaxResultSize ) {
296 $this->setWarning(
297 "This result was truncated because it would otherwise be larger than the " .
298 "limit of {$wgAPIMaxResultSize} bytes" );
300 return false;
302 $this->mSize = $newsize;
305 $addOnTop = $flags & ApiResult::ADD_ON_TOP;
306 if ( $path !== null ) {
307 foreach ( (array)$path as $p ) {
308 if ( !isset( $data[$p] ) ) {
309 if ( $addOnTop ) {
310 $data = array( $p => array() ) + $data;
311 $addOnTop = false;
312 } else {
313 $data[$p] = array();
316 $data = &$data[$p];
320 if ( !$name ) {
321 // Add list element
322 if ( $addOnTop ) {
323 // This element needs to be inserted in the beginning
324 // Numerical indexes will be renumbered
325 array_unshift( $data, $value );
326 } else {
327 // Add new value at the end
328 $data[] = $value;
330 } else {
331 // Add named element
332 self::setElement( $data, $name, $value, $flags );
335 return true;
339 * Add a parsed limit=max to the result.
341 * @param $moduleName string
342 * @param $limit int
344 public function setParsedLimit( $moduleName, $limit ) {
345 // Add value, allowing overwriting
346 $this->addValue( 'limits', $moduleName, $limit, ApiResult::OVERRIDE );
350 * Unset a value previously added to the result set.
351 * Fails silently if the value isn't found.
352 * For parameters, see addValue()
353 * @param $path array|null
354 * @param $name string
356 public function unsetValue( $path, $name ) {
357 $data = &$this->mData;
358 if ( $path !== null ) {
359 foreach ( (array)$path as $p ) {
360 if ( !isset( $data[$p] ) ) {
361 return;
363 $data = &$data[$p];
366 $this->mSize -= self::size( $data[$name] );
367 unset( $data[$name] );
371 * Ensure all values in this result are valid UTF-8.
373 public function cleanUpUTF8() {
374 array_walk_recursive( $this->mData, array( 'ApiResult', 'cleanUp_helper' ) );
378 * Callback function for cleanUpUTF8()
380 * @param $s string
382 private static function cleanUp_helper( &$s ) {
383 if ( !is_string( $s ) ) {
384 return;
386 global $wgContLang;
387 $s = $wgContLang->normalize( $s );
391 * Converts a Status object to an array suitable for addValue
392 * @param Status $status
393 * @param string $errorType
394 * @return array
396 public function convertStatusToArray( $status, $errorType = 'error' ) {
397 if ( $status->isGood() ) {
398 return array();
401 $result = array();
402 foreach ( $status->getErrorsByType( $errorType ) as $error ) {
403 $this->setIndexedTagName( $error['params'], 'param' );
404 $result[] = $error;
406 $this->setIndexedTagName( $result, $errorType );
408 return $result;
411 public function execute() {
412 ApiBase::dieDebug( __METHOD__, 'execute() is not supported on Result object' );