No more undefined usage of rev{Start,End}Id warnings
[mediawiki.git] / includes / api / ApiResult.php
blob798b227567148e1ea179d2cc55767e13b2f0b382
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 array's modifications.
30 * As various modules execute, they add different pieces of information to this result,
31 * 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 outputed 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 private $mData, $mIsRawMode, $mSize, $mCheckingSize;
48 /**
49 * Constructor
50 * @param $main ApiMain object
52 public function __construct( $main ) {
53 parent::__construct( $main, 'result' );
54 $this->mIsRawMode = false;
55 $this->mCheckingSize = true;
56 $this->reset();
59 /**
60 * Clear the current result data.
62 public function reset() {
63 $this->mData = array();
64 $this->mSize = 0;
67 /**
68 * Call this function when special elements such as '_element'
69 * are needed by the formatter, for example in XML printing.
71 public function setRawMode() {
72 $this->mIsRawMode = true;
75 /**
76 * Returns true whether the formatter requested raw data.
77 * @return bool
79 public function getIsRawMode() {
80 return $this->mIsRawMode;
83 /**
84 * Get the result's internal data array (read-only)
85 * @return array
87 public function getData() {
88 return $this->mData;
91 /**
92 * Get the 'real' size of a result item. This means the strlen() of the item,
93 * or the sum of the strlen()s of the elements if the item is an array.
94 * @param $value mixed
95 * @return int
97 public static function size( $value ) {
98 $s = 0;
99 if ( is_array( $value ) ) {
100 foreach ( $value as $v ) {
101 $s += self::size( $v );
103 } elseif ( !is_object( $value ) ) {
104 // Objects can't always be cast to string
105 $s = strlen( $value );
107 return $s;
111 * Get the size of the result, i.e. the amount of bytes in it
112 * @return int
114 public function getSize() {
115 return $this->mSize;
119 * Disable size checking in addValue(). Don't use this unless you
120 * REALLY know what you're doing. Values added while size checking
121 * was disabled will not be counted (ever)
123 public function disableSizeCheck() {
124 $this->mCheckingSize = false;
128 * Re-enable size checking in addValue()
130 public function enableSizeCheck() {
131 $this->mCheckingSize = true;
135 * Add an output value to the array by name.
136 * Verifies that value with the same name has not been added before.
137 * @param $arr array to add $value to
138 * @param $name string Index of $arr to add $value at
139 * @param $value mixed
140 * @param $overwrite bool Whether overwriting an existing element is allowed
142 public static function setElement( &$arr, $name, $value, $overwrite = false ) {
143 if ( $arr === null || $name === null || $value === null || !is_array( $arr ) || is_array( $name ) ) {
144 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
147 if ( !isset ( $arr[$name] ) || $overwrite ) {
148 $arr[$name] = $value;
149 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
150 $merged = array_intersect_key( $arr[$name], $value );
151 if ( !count( $merged ) ) {
152 $arr[$name] += $value;
153 } else {
154 ApiBase::dieDebug( __METHOD__, "Attempting to merge element $name" );
156 } else {
157 ApiBase::dieDebug( __METHOD__, "Attempting to add element $name=$value, existing value is {$arr[$name]}" );
162 * Adds a content element to an array.
163 * Use this function instead of hardcoding the '*' element.
164 * @param $arr array to add the content element to
165 * @param $value Mixed
166 * @param $subElemName string when present, content element is created
167 * as a sub item of $arr. Use this parameter to create elements in
168 * format <elem>text</elem> without attributes
170 public static function setContent( &$arr, $value, $subElemName = null ) {
171 if ( is_array( $value ) ) {
172 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
174 if ( is_null( $subElemName ) ) {
175 ApiResult::setElement( $arr, '*', $value );
176 } else {
177 if ( !isset( $arr[$subElemName] ) ) {
178 $arr[$subElemName] = array();
180 ApiResult::setElement( $arr[$subElemName], '*', $value );
185 * In case the array contains indexed values (in addition to named),
186 * give all indexed values the given tag name. This function MUST be
187 * called on every array that has numerical indexes.
188 * @param $arr array
189 * @param $tag string Tag name
191 public function setIndexedTagName( &$arr, $tag ) {
192 // In raw mode, add the '_element', otherwise just ignore
193 if ( !$this->getIsRawMode() ) {
194 return;
196 if ( $arr === null || $tag === null || !is_array( $arr ) || is_array( $tag ) ) {
197 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
199 // Do not use setElement() as it is ok to call this more than once
200 $arr['_element'] = $tag;
204 * Calls setIndexedTagName() on each sub-array of $arr
205 * @param $arr array
206 * @param $tag string Tag name
208 public function setIndexedTagName_recursive( &$arr, $tag ) {
209 if ( !is_array( $arr ) ) {
210 return;
212 foreach ( $arr as &$a ) {
213 if ( !is_array( $a ) ) {
214 continue;
216 $this->setIndexedTagName( $a, $tag );
217 $this->setIndexedTagName_recursive( $a, $tag );
222 * Calls setIndexedTagName() on an array already in the result.
223 * Don't specify a path to a value that's not in the result, or
224 * you'll get nasty errors.
225 * @param $path array Path to the array, like addValue()'s $path
226 * @param $tag string
228 public function setIndexedTagName_internal( $path, $tag ) {
229 $data = &$this->mData;
230 foreach ( (array)$path as $p ) {
231 if ( !isset( $data[$p] ) ) {
232 $data[$p] = array();
234 $data = &$data[$p];
236 if ( is_null( $data ) ) {
237 return;
239 $this->setIndexedTagName( $data, $tag );
243 * Add value to the output data at the given path.
244 * Path can be an indexed array, each element specifying the branch at which to add the new
245 * value. Setting $path to array('a','b','c') is equivalent to data['a']['b']['c'] = $value.
246 * If $path is null, the value will be inserted at the data root.
247 * If $name is empty, the $value is added as a next list element data[] = $value.
249 * @param $path array|string|null
250 * @param $name string
251 * @param $value mixed
252 * @param $overwrite bool
254 * @return bool True if $value fits in the result, false if not
256 public function addValue( $path, $name, $value, $overwrite = false ) {
257 global $wgAPIMaxResultSize;
259 $data = &$this->mData;
260 if ( $this->mCheckingSize ) {
261 $newsize = $this->mSize + self::size( $value );
262 if ( $newsize > $wgAPIMaxResultSize ) {
263 $this->setWarning(
264 "This result was truncated because it would otherwise be larger than the " .
265 "limit of {$wgAPIMaxResultSize} bytes" );
266 return false;
268 $this->mSize = $newsize;
271 if ( !is_null( $path ) ) {
272 if ( is_array( $path ) ) {
273 foreach ( $path as $p ) {
274 if ( !isset( $data[$p] ) ) {
275 $data[$p] = array();
277 $data = &$data[$p];
279 } else {
280 if ( !isset( $data[$path] ) ) {
281 $data[$path] = array();
283 $data = &$data[$path];
287 if ( !$name ) {
288 $data[] = $value; // Add list element
289 } else {
290 self::setElement( $data, $name, $value, $overwrite ); // Add named element
292 return true;
296 * Add a parsed limit=max to the result.
298 * @param $moduleName string
299 * @param $limit int
301 public function setParsedLimit( $moduleName, $limit ) {
302 // Add value, allowing overwriting
303 $this->addValue( 'limits', $moduleName, $limit, true );
307 * Unset a value previously added to the result set.
308 * Fails silently if the value isn't found.
309 * For parameters, see addValue()
310 * @param $path array
311 * @param $name string
313 public function unsetValue( $path, $name ) {
314 $data = &$this->mData;
315 if ( !is_null( $path ) ) {
316 foreach ( (array)$path as $p ) {
317 if ( !isset( $data[$p] ) ) {
318 return;
320 $data = &$data[$p];
323 $this->mSize -= self::size( $data[$name] );
324 unset( $data[$name] );
328 * Ensure all values in this result are valid UTF-8.
330 public function cleanUpUTF8() {
331 array_walk_recursive( $this->mData, array( 'ApiResult', 'cleanUp_helper' ) );
335 * Callback function for cleanUpUTF8()
337 * @param $s string
339 private static function cleanUp_helper( &$s ) {
340 if ( !is_string( $s ) ) {
341 return;
343 global $wgContLang;
344 $s = $wgContLang->normalize( $s );
348 * Converts a Status object to an array suitable for addValue
349 * @param Status $status
350 * @param string $errorType
351 * @return array
353 public function convertStatusToArray( $status, $errorType = 'error' ) {
354 if ( $status->isGood() ) {
355 return array();
358 $result = array();
359 foreach ( $status->getErrorsByType( $errorType ) as $error ) {
360 $this->setIndexedTagName( $error['params'], 'param' );
361 $result[] = $error;
363 $this->setIndexedTagName( $result, $errorType );
364 return $result;
367 public function execute() {
368 ApiBase::dieDebug( __METHOD__, 'execute() is not supported on Result object' );
371 public function getVersion() {
372 return __CLASS__ . ': $Id$';