490b8310dcad00eda9dcc9debd918d0cfc2b1613
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
22 * This class represents the result of the API operations.
23 * It simply wraps a nested array() structure, adding some functions to simplify
24 * array's modifications. As various modules execute, they add different pieces
25 * of information to this result, structuring it as it will be given to the client.
27 * Each subarray may either be a dictionary - key-value pairs with unique keys,
28 * or lists, where the items are added using $data[] = $value notation.
30 * @since 1.25 this is no longer a subclass of ApiBase
33 class ApiResult
implements ApiSerializable
{
36 * Override existing value in addValue(), setValue(), and similar functions
42 * For addValue(), setValue() and similar functions, if the value does not
43 * exist, add it as the first element. In case the new value has no name
44 * (numerical index), all indexes will be renumbered.
50 * For addValue() and similar functions, do not check size while adding a value
51 * Don't use this unless you REALLY know what you're doing.
52 * Values added while the size checking was disabled will never be counted.
53 * Ignored for setValue() and similar functions.
56 const NO_SIZE_CHECK
= 4;
59 * For addValue(), setValue() and similar functions, do not validate data.
60 * Also disables size checking. If you think you need to use this, you're
64 const NO_VALIDATE
= 12;
67 * Key for the 'indexed tag name' metadata item. Value is string.
70 const META_INDEXED_TAG_NAME
= '_element';
73 * Key for the 'subelements' metadata item. Value is string[].
76 const META_SUBELEMENTS
= '_subelements';
79 * Key for the 'preserve keys' metadata item. Value is string[].
82 const META_PRESERVE_KEYS
= '_preservekeys';
85 * Key for the 'content' metadata item. Value is string.
88 const META_CONTENT
= '_content';
91 * Key for the 'type' metadata item. Value is one of the following strings:
92 * - default: Like 'array' if all (non-metadata) keys are numeric with no
93 * gaps, otherwise like 'assoc'.
94 * - array: Keys are used for ordering, but are not output. In a format
95 * like JSON, outputs as [].
96 * - assoc: In a format like JSON, outputs as {}.
97 * - kvp: For a format like XML where object keys have a restricted
98 * character set, use an alternative output format. For example,
99 * <container><item name="key">value</item></container> rather than
100 * <container key="value" />
101 * - BCarray: Like 'array' normally, 'default' in backwards-compatibility mode.
102 * - BCassoc: Like 'assoc' normally, 'default' in backwards-compatibility mode.
103 * - BCkvp: Like 'kvp' normally. In backwards-compatibility mode, forces
104 * the alternative output format for all formats, for example
105 * [{"name":key,"*":value}] in JSON. META_KVP_KEY_NAME must also be set.
108 const META_TYPE
= '_type';
111 * Key (rather than "name" or other default) for when META_TYPE is 'kvp' or
112 * 'BCkvp'. Value is string.
115 const META_KVP_KEY_NAME
= '_kvpkeyname';
118 * Key for the 'BC bools' metadata item. Value is string[].
119 * Note no setter is provided.
122 const META_BC_BOOLS
= '_BC_bools';
125 * Key for the 'BC subelements' metadata item. Value is string[].
126 * Note no setter is provided.
129 const META_BC_SUBELEMENTS
= '_BC_subelements';
131 private $data, $size, $maxSize;
132 private $errorFormatter;
135 private $isRawMode, $checkingSize, $mainForContinuation;
138 * @param int|bool $maxSize Maximum result "size", or false for no limit
139 * @since 1.25 Takes an integer|bool rather than an ApiMain
141 public function __construct( $maxSize ) {
142 if ( $maxSize instanceof ApiMain
) {
143 /// @todo: After fixing Wikidata unit tests, warn
144 //wfDeprecated( 'Passing ApiMain to ' . __METHOD__ . ' is deprecated', '1.25' );
145 $this->errorFormatter
= $maxSize->getErrorFormatter();
146 $this->mainForContinuation
= $maxSize;
147 $maxSize = $maxSize->getConfig()->get( 'APIMaxResultSize' );
150 $this->maxSize
= $maxSize;
151 $this->isRawMode
= false;
152 $this->checkingSize
= true;
157 * Set the error formatter
159 * @param ApiErrorFormatter $formatter
161 public function setErrorFormatter( ApiErrorFormatter
$formatter ) {
162 $this->errorFormatter
= $formatter;
166 * Allow for adding one ApiResult into another
170 public function serializeForApiResult() {
174 /************************************************************************//**
180 * Clear the current result data.
182 public function reset() {
183 $this->data
= array();
188 * Get the result data array
190 * The returned value should be considered read-only.
192 * Transformations include:
194 * Custom: (callable) Applied before other transformations. Signature is
195 * function ( &$data, &$metadata ), return value is ignored. Called for
198 * BC: (array) This transformation does various adjustments to bring the
199 * output in line with the pre-1.25 result format. The value array is a
200 * list of flags: 'nobool', 'no*', 'nosub'.
201 * - Boolean-valued items are changed to '' if true or removed if false,
202 * unless listed in META_BC_BOOLS. This may be skipped by including
203 * 'nobool' in the value array.
204 * - The tag named by META_CONTENT is renamed to '*', and META_CONTENT is
205 * set to '*'. This may be skipped by including 'no*' in the value
207 * - Tags listed in META_BC_SUBELEMENTS will have their values changed to
208 * array( '*' => $value ). This may be skipped by including 'nosub' in
210 * - If META_TYPE is 'BCarray', set it to 'default'
211 * - If META_TYPE is 'BCassoc', set it to 'default'
212 * - If META_TYPE is 'BCkvp', perform the transformation (even if
213 * the Types transformation is not being applied).
215 * Types: (assoc) Apply transformations based on META_TYPE. The values
216 * array is an associative array with the following possible keys:
217 * - AssocAsObject: (bool) If true, return arrays with META_TYPE 'assoc'
219 * - ArmorKVP: (string) If provided, transform arrays with META_TYPE 'kvp'
220 * and 'BCkvp' into arrays of two-element arrays, something like this:
222 * foreach ( $input as $key => $value ) {
224 * $pair[$META_KVP_KEY_NAME ?: $ArmorKVP_value] = $key;
225 * ApiResult::setContentValue( $pair, 'value', $value );
229 * Strip: (string) Strips metadata keys from the result.
230 * - 'all': Strip all metadata, recursively
231 * - 'base': Strip metadata at the top-level only.
232 * - 'none': Do not strip metadata.
233 * - 'bc': Like 'all', but leave certain pre-1.25 keys.
236 * @param array|string|null $path Path to fetch, see ApiResult::addValue
237 * @param array $transforms See above
238 * @return mixed Result data, or null if not found
240 public function getResultData( $path = array(), $transforms = array() ) {
241 $path = (array)$path;
243 return self
::applyTransformations( $this->data
, $transforms );
246 $last = array_pop( $path );
247 $ret = &$this->path( $path, 'dummy' );
248 if ( !isset( $ret[$last] ) ) {
250 } elseif ( is_array( $ret[$last] ) ) {
251 return self
::applyTransformations( $ret[$last], $transforms );
258 * Get the size of the result, i.e. the amount of bytes in it
261 public function getSize() {
266 * Add an output value to the array by name.
268 * Verifies that value with the same name has not been added before.
271 * @param array &$arr To add $value to
272 * @param string|int|null $name Index of $arr to add $value at,
273 * or null to use the next numeric index.
274 * @param mixed $value
275 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
277 public static function setValue( array &$arr, $name, $value, $flags = 0 ) {
278 if ( $name === null ) {
279 if ( $flags & ApiResult
::ADD_ON_TOP
) {
280 array_unshift( $arr, $value );
282 array_push( $arr, $value );
287 if ( !( $flags & ApiResult
::NO_VALIDATE
) ) {
288 $value = self
::validateValue( $value );
291 $exists = isset( $arr[$name] );
292 if ( !$exists ||
( $flags & ApiResult
::OVERRIDE
) ) {
293 if ( !$exists && ( $flags & ApiResult
::ADD_ON_TOP
) ) {
294 $arr = array( $name => $value ) +
$arr;
296 $arr[$name] = $value;
298 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
299 $conflicts = array_intersect_key( $arr[$name], $value );
301 $arr[$name] +
= $value;
303 $keys = join( ', ', array_keys( $conflicts ) );
304 throw new RuntimeException( "Conflicting keys ($keys) when attempting to merge element $name" );
307 throw new RuntimeException( "Attempting to add element $name=$value, existing value is {$arr[$name]}" );
312 * Validate a value for addition to the result
313 * @param mixed $value
315 private static function validateValue( $value ) {
318 if ( is_object( $value ) ) {
319 // Note we use is_callable() here instead of instanceof because
320 // ApiSerializable is an informal protocol (see docs there for details).
321 if ( is_callable( array( $value, 'serializeForApiResult' ) ) ) {
323 $value = $value->serializeForApiResult();
324 if ( is_object( $value ) ) {
325 throw new UnexpectedValueException(
326 get_class( $oldValue ) . "::serializeForApiResult() returned an object of class " .
331 // Recursive call instead of fall-through so we can throw a
332 // better exception message.
334 return self
::validateValue( $value );
335 } catch ( Exception
$ex ) {
336 throw new UnexpectedValueException(
337 get_class( $oldValue ) . "::serializeForApiResult() returned an invalid value: " .
343 } elseif ( is_callable( array( $value, '__toString' ) ) ) {
344 $value = (string)$value;
346 $value = (array)$value +
array( self
::META_TYPE
=> 'assoc' );
349 if ( is_array( $value ) ) {
350 foreach ( $value as $k => $v ) {
351 $value[$k] = self
::validateValue( $v );
353 } elseif ( is_float( $value ) && !is_finite( $value ) ) {
354 throw new InvalidArgumentException( "Cannot add non-finite floats to ApiResult" );
355 } elseif ( is_string( $value ) ) {
356 $value = $wgContLang->normalize( $value );
357 } elseif ( $value !== null && !is_scalar( $value ) ) {
358 $type = gettype( $value );
359 if ( is_resource( $value ) ) {
360 $type .= '(' . get_resource_type( $value ) . ')';
362 throw new InvalidArgumentException( "Cannot add $type to ApiResult" );
369 * Add value to the output data at the given path.
371 * Path can be an indexed array, each element specifying the branch at which to add the new
372 * value. Setting $path to array('a','b','c') is equivalent to data['a']['b']['c'] = $value.
373 * If $path is null, the value will be inserted at the data root.
375 * @param array|string|int|null $path
376 * @param string|int|null $name See ApiResult::setValue()
377 * @param mixed $value
378 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
379 * This parameter used to be boolean, and the value of OVERRIDE=1 was specifically
380 * chosen so that it would be backwards compatible with the new method signature.
381 * @return bool True if $value fits in the result, false if not
382 * @since 1.21 int $flags replaced boolean $override
384 public function addValue( $path, $name, $value, $flags = 0 ) {
385 $arr = &$this->path( $path, ( $flags & ApiResult
::ADD_ON_TOP
) ?
'prepend' : 'append' );
387 if ( $this->checkingSize
&& !( $flags & ApiResult
::NO_SIZE_CHECK
) ) {
388 $newsize = $this->size + self
::valueSize( $value );
389 if ( $this->maxSize
!== false && $newsize > $this->maxSize
) {
390 /// @todo Add i18n message when replacing calls to ->setWarning()
391 $msg = new ApiRawMessage( 'This result was truncated because it would otherwise ' .
392 ' be larger than the limit of $1 bytes', 'truncatedresult' );
393 $msg->numParams( $this->maxSize
);
394 $this->errorFormatter
->addWarning( 'result', $msg );
397 $this->size
= $newsize;
400 self
::setValue( $arr, $name, $value, $flags );
405 * Remove an output value to the array by name.
406 * @param array &$arr To remove $value from
407 * @param string|int $name Index of $arr to remove
408 * @return mixed Old value, or null
410 public static function unsetValue( array &$arr, $name ) {
412 if ( isset( $arr[$name] ) ) {
414 unset( $arr[$name] );
420 * Remove value from the output data at the given path.
423 * @param array|string|null $path See ApiResult::addValue()
424 * @param string|int|null $name Index to remove at $path.
425 * If null, $path itself is removed.
426 * @param int $flags Flags used when adding the value
427 * @return mixed Old value, or null
429 public function removeValue( $path, $name, $flags = 0 ) {
430 $path = (array)$path;
431 if ( $name === null ) {
433 throw new InvalidArgumentException( 'Cannot remove the data root' );
435 $name = array_pop( $path );
437 $ret = self
::unsetValue( $this->path( $path, 'dummy' ), $name );
438 if ( $this->checkingSize
&& !( $flags & ApiResult
::NO_SIZE_CHECK
) ) {
439 $newsize = $this->size
- self
::valueSize( $ret );
440 $this->size
= max( $newsize, 0 );
446 * Add an output value to the array by name and mark as META_CONTENT.
449 * @param array &$arr To add $value to
450 * @param string|int $name Index of $arr to add $value at.
451 * @param mixed $value
452 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
454 public static function setContentValue( array &$arr, $name, $value, $flags = 0 ) {
455 if ( $name === null ) {
456 throw new InvalidArgumentException( 'Content value must be named' );
458 self
::setContentField( $arr, $name, $flags );
459 self
::setValue( $arr, $name, $value, $flags );
463 * Add value to the output data at the given path and mark as META_CONTENT
466 * @param array|string|null $path See ApiResult::addValue()
467 * @param string|int $name See ApiResult::setValue()
468 * @param mixed $value
469 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
470 * @return bool True if $value fits in the result, false if not
472 public function addContentValue( $path, $name, $value, $flags = 0 ) {
473 if ( $name === null ) {
474 throw new InvalidArgumentException( 'Content value must be named' );
476 $this->addContentField( $path, $name, $flags );
477 $this->addValue( $path, $name, $value, $flags );
481 * Add the numeric limit for a limit=max to the result.
484 * @param string $moduleName
487 public function addParsedLimit( $moduleName, $limit ) {
488 // Add value, allowing overwriting
489 $this->addValue( 'limits', $moduleName, $limit,
490 ApiResult
::OVERRIDE | ApiResult
::NO_SIZE_CHECK
);
495 /************************************************************************//**
501 * Set the name of the content field name (META_CONTENT)
505 * @param string|int $name Name of the field
506 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
508 public static function setContentField( array &$arr, $name, $flags = 0 ) {
509 if ( isset( $arr[self
::META_CONTENT
] ) &&
510 isset( $arr[$arr[self
::META_CONTENT
]] ) &&
511 !( $flags & self
::OVERRIDE
)
513 throw new RuntimeException(
514 "Attempting to set content element as $name when " . $arr[self
::META_CONTENT
] .
515 " is already set as the content element"
518 $arr[self
::META_CONTENT
] = $name;
522 * Set the name of the content field name (META_CONTENT)
525 * @param array|string|null $path See ApiResult::addValue()
526 * @param string|int $name Name of the field
527 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
529 public function addContentField( $path, $name, $flags = 0 ) {
530 $arr = &$this->path( $path, ( $flags & ApiResult
::ADD_ON_TOP
) ?
'prepend' : 'append' );
531 self
::setContentField( $arr, $name, $flags );
535 * Causes the elements with the specified names to be output as
536 * subelements rather than attributes.
537 * @since 1.25 is static
539 * @param array|string|int $names The element name(s) to be output as subelements
541 public static function setSubelementsList( array &$arr, $names ) {
542 if ( !isset( $arr[self
::META_SUBELEMENTS
] ) ) {
543 $arr[self
::META_SUBELEMENTS
] = (array)$names;
545 $arr[self
::META_SUBELEMENTS
] = array_merge( $arr[self
::META_SUBELEMENTS
], (array)$names );
550 * Causes the elements with the specified names to be output as
551 * subelements rather than attributes.
553 * @param array|string|null $path See ApiResult::addValue()
554 * @param array|string|int $names The element name(s) to be output as subelements
556 public function addSubelementsList( $path, $names ) {
557 $arr = &$this->path( $path );
558 self
::setSubelementsList( $arr, $names );
562 * Causes the elements with the specified names to be output as
563 * attributes (when possible) rather than as subelements.
566 * @param array|string|int $names The element name(s) to not be output as subelements
568 public static function unsetSubelementsList( array &$arr, $names ) {
569 if ( isset( $arr[self
::META_SUBELEMENTS
] ) ) {
570 $arr[self
::META_SUBELEMENTS
] = array_diff( $arr[self
::META_SUBELEMENTS
], (array)$names );
575 * Causes the elements with the specified names to be output as
576 * attributes (when possible) rather than as subelements.
578 * @param array|string|null $path See ApiResult::addValue()
579 * @param array|string|int $names The element name(s) to not be output as subelements
581 public function removeSubelementsList( $path, $names ) {
582 $arr = &$this->path( $path );
583 self
::unsetSubelementsList( $arr, $names );
587 * Set the tag name for numeric-keyed values in XML format
588 * @since 1.25 is static
590 * @param string $tag Tag name
592 public static function setIndexedTagName( array &$arr, $tag ) {
593 if ( !is_string( $tag ) ) {
594 throw new InvalidArgumentException( 'Bad tag name' );
596 $arr[self
::META_INDEXED_TAG_NAME
] = $tag;
600 * Set the tag name for numeric-keyed values in XML format
602 * @param array|string|null $path See ApiResult::addValue()
603 * @param string $tag Tag name
605 public function addIndexedTagName( $path, $tag ) {
606 $arr = &$this->path( $path );
607 self
::setIndexedTagName( $arr, $tag );
611 * Set indexed tag name on $arr and all subarrays
615 * @param string $tag Tag name
617 public static function setIndexedTagNameRecursive( array &$arr, $tag ) {
618 if ( !is_string( $tag ) ) {
619 throw new InvalidArgumentException( 'Bad tag name' );
621 $arr[self
::META_INDEXED_TAG_NAME
] = $tag;
622 foreach ( $arr as $k => &$v ) {
623 if ( !self
::isMetadataKey( $k ) && is_array( $v ) ) {
624 self
::setIndexedTagNameRecursive( $v, $tag );
630 * Set indexed tag name on $path and all subarrays
633 * @param array|string|null $path See ApiResult::addValue()
634 * @param string $tag Tag name
636 public function addIndexedTagNameRecursive( $path, $tag ) {
637 $arr = &$this->path( $path );
638 self
::setIndexedTagNameRecursive( $arr, $tag );
642 * Preserve specified keys.
644 * This prevents XML name mangling and preventing keys from being removed
645 * by self::stripMetadata().
649 * @param array|string $names The element name(s) to preserve
651 public static function setPreserveKeysList( array &$arr, $names ) {
652 if ( !isset( $arr[self
::META_PRESERVE_KEYS
] ) ) {
653 $arr[self
::META_PRESERVE_KEYS
] = (array)$names;
655 $arr[self
::META_PRESERVE_KEYS
] = array_merge( $arr[self
::META_PRESERVE_KEYS
], (array)$names );
660 * Preserve specified keys.
662 * @see self::setPreserveKeysList()
663 * @param array|string|null $path See ApiResult::addValue()
664 * @param array|string $names The element name(s) to preserve
666 public function addPreserveKeysList( $path, $names ) {
667 $arr = &$this->path( $path );
668 self
::setPreserveKeysList( $arr, $names );
672 * Don't preserve specified keys.
674 * @see self::setPreserveKeysList()
676 * @param array|string $names The element name(s) to not preserve
678 public static function unsetPreserveKeysList( array &$arr, $names ) {
679 if ( isset( $arr[self
::META_PRESERVE_KEYS
] ) ) {
680 $arr[self
::META_PRESERVE_KEYS
] = array_diff( $arr[self
::META_PRESERVE_KEYS
], (array)$names );
685 * Don't preserve specified keys.
687 * @see self::setPreserveKeysList()
688 * @param array|string|null $path See ApiResult::addValue()
689 * @param array|string $names The element name(s) to not preserve
691 public function removePreserveKeysList( $path, $names ) {
692 $arr = &$this->path( $path );
693 self
::unsetPreserveKeysList( $arr, $names );
697 * Set the array data type
701 * @param string $type See ApiResult::META_TYPE
702 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
704 public static function setArrayType( array &$arr, $type, $kvpKeyName = null ) {
705 if ( !in_array( $type, array( 'default', 'array', 'assoc', 'kvp', 'BCarray', 'BCassoc', 'BCkvp' ), true ) ) {
706 throw new InvalidArgumentException( 'Bad type' );
708 $arr[self
::META_TYPE
] = $type;
709 if ( is_string( $kvpKeyName ) ) {
710 $arr[self
::META_KVP_KEY_NAME
] = $kvpKeyName;
715 * Set the array data type for a path
717 * @param array|string|null $path See ApiResult::addValue()
718 * @param string $type See ApiResult::META_TYPE
719 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
721 public function addArrayType( $path, $tag, $kvpKeyName = null ) {
722 $arr = &$this->path( $path );
723 self
::setArrayType( $arr, $tag, $kvpKeyName );
727 * Set the array data type recursively
730 * @param string $type See ApiResult::META_TYPE
731 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
733 public static function setArrayTypeRecursive( array &$arr, $type, $kvpKeyName = null ) {
734 self
::setArrayType( $arr, $type, $kvpKeyName );
735 foreach ( $arr as $k => &$v ) {
736 if ( !self
::isMetadataKey( $k ) && is_array( $v ) ) {
737 self
::setArrayTypeRecursive( $v, $type, $kvpKeyName );
743 * Set the array data type for a path recursively
745 * @param array|string|null $path See ApiResult::addValue()
746 * @param string $type See ApiResult::META_TYPE
747 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
749 public function addArrayTypeRecursive( $path, $tag, $kvpKeyName = null ) {
750 $arr = &$this->path( $path );
751 self
::setArrayTypeRecursive( $arr, $tag, $kvpKeyName );
756 /************************************************************************//**
762 * Test whether a key should be considered metadata
767 public static function isMetadataKey( $key ) {
768 return substr( $key, 0, 1 ) === '_';
772 * Apply transformations to an array, returning the transformed array.
774 * @see ApiResult::getResultData()
777 * @param array $transforms
778 * @return array|object
780 protected static function applyTransformations( array $dataIn, array $transforms ) {
781 $strip = isset( $transforms['Strip'] ) ?
$transforms['Strip'] : 'none';
782 if ( $strip === 'base' ) {
783 $transforms['Strip'] = 'none';
785 $transformTypes = isset( $transforms['Types'] ) ?
$transforms['Types'] : null;
786 if ( $transformTypes !== null && !is_array( $transformTypes ) ) {
787 throw new InvalidArgumentException( __METHOD__
. ':Value for "Types" must be an array' );
791 $data = self
::stripMetadataNonRecursive( $dataIn, $metadata );
793 if ( isset( $transforms['Custom'] ) ) {
794 if ( !is_callable( $transforms['Custom'] ) ) {
795 throw new InvalidArgumentException( __METHOD__
. ': Value for "Custom" must be callable' );
797 call_user_func_array( $transforms['Custom'], array( &$data, &$metadata ) );
800 if ( ( isset( $transforms['BC'] ) ||
$transformTypes !== null ) &&
801 isset( $metadata[self
::META_TYPE
] ) && $metadata[self
::META_TYPE
] === 'BCkvp' &&
802 !isset( $metadata[self
::META_KVP_KEY_NAME
] )
804 throw new UnexpectedValueException( 'Type "BCkvp" used without setting ' .
805 'ApiResult::META_KVP_KEY_NAME metadata item' );
808 // BC transformations
811 if ( isset( $transforms['BC'] ) ) {
812 if ( !is_array( $transforms['BC'] ) ) {
813 throw new InvalidArgumentException( __METHOD__
. ':Value for "BC" must be an array' );
815 if ( !in_array( 'nobool', $transforms['BC'], true ) ) {
816 $boolKeys = isset( $metadata[self
::META_BC_BOOLS
] )
817 ?
array_flip( $metadata[self
::META_BC_BOOLS
] )
821 if ( !in_array( 'no*', $transforms['BC'], true ) &&
822 isset( $metadata[self
::META_CONTENT
] ) && $metadata[self
::META_CONTENT
] !== '*'
824 $k = $metadata[self
::META_CONTENT
];
825 $data['*'] = $data[$k];
827 $metadata[self
::META_CONTENT
] = '*';
830 if ( !in_array( 'nosub', $transforms['BC'], true ) &&
831 isset( $metadata[self
::META_BC_SUBELEMENTS
] )
833 foreach ( $metadata[self
::META_BC_SUBELEMENTS
] as $k ) {
836 self
::META_CONTENT
=> '*',
837 self
::META_TYPE
=> 'assoc',
842 if ( isset( $metadata[self
::META_TYPE
] ) ) {
843 switch ( $metadata[self
::META_TYPE
] ) {
846 $metadata[self
::META_TYPE
] = 'default';
849 $transformTypes['ArmorKVP'] = $metadata[self
::META_KVP_KEY_NAME
];
855 // Figure out type, do recursive calls, and do boolean transform if necessary
856 $defaultType = 'array';
858 foreach ( $data as $k => &$v ) {
859 $v = is_array( $v ) ? self
::applyTransformations( $v, $transforms ) : $v;
860 if ( $boolKeys !== null && is_bool( $v ) && !isset( $boolKeys[$k] ) ) {
867 if ( is_string( $k ) ) {
868 $defaultType = 'assoc';
869 } elseif ( $k > $maxKey ) {
875 // Determine which metadata to keep
879 $keepMetadata = array();
882 $keepMetadata = &$metadata;
885 $keepMetadata = array_intersect_key( $metadata, array(
886 self
::META_INDEXED_TAG_NAME
=> 1,
887 self
::META_SUBELEMENTS
=> 1,
891 throw new InvalidArgumentException( __METHOD__
. ': Unknown value for "Strip"' );
894 // Type transformation
895 if ( $transformTypes !== null ) {
896 if ( $defaultType === 'array' && $maxKey !== count( $data ) - 1 ) {
897 $defaultType = 'assoc';
900 // Override type, if provided
901 $type = $defaultType;
902 if ( isset( $metadata[self
::META_TYPE
] ) && $metadata[self
::META_TYPE
] !== 'default' ) {
903 $type = $metadata[self
::META_TYPE
];
905 if ( ( $type === 'kvp' ||
$type === 'BCkvp' ) &&
906 empty( $transformTypes['ArmorKVP'] )
909 } elseif ( $type === 'BCarray' ) {
911 } elseif ( $type === 'BCassoc' ) {
915 // Apply transformation
918 $metadata[self
::META_TYPE
] = 'assoc';
919 $data +
= $keepMetadata;
920 return empty( $transformTypes['AssocAsObject'] ) ?
$data : (object)$data;
924 $data = array_values( $data );
925 $metadata[self
::META_TYPE
] = 'array';
926 return $data +
$keepMetadata;
930 $key = isset( $metadata[self
::META_KVP_KEY_NAME
] )
931 ?
$metadata[self
::META_KVP_KEY_NAME
]
932 : $transformTypes['ArmorKVP'];
933 $valKey = isset( $transforms['BC'] ) ?
'*' : 'value';
934 $assocAsObject = !empty( $transformTypes['AssocAsObject'] );
937 foreach ( $data as $k => $v ) {
942 if ( $strip === 'none' ) {
944 self
::META_PRESERVE_KEYS
=> array( $key ),
945 self
::META_CONTENT
=> $valKey,
946 self
::META_TYPE
=> 'assoc',
949 $ret[] = $assocAsObject ?
(object)$item : $item;
951 $metadata[self
::META_TYPE
] = 'array';
953 return $ret +
$keepMetadata;
956 throw new UnexpectedValueException( "Unknown type '$type'" );
959 return $data +
$keepMetadata;
964 * Recursively remove metadata keys from a data array or object
966 * Note this removes all potential metadata keys, not just the defined
970 * @param array|object $data
971 * @return array|object
973 public static function stripMetadata( $data ) {
974 if ( is_array( $data ) ||
is_object( $data ) ) {
975 $isObj = is_object( $data );
977 $data = (array)$data;
979 $preserveKeys = isset( $data[self
::META_PRESERVE_KEYS
] )
980 ?
(array)$data[self
::META_PRESERVE_KEYS
]
982 foreach ( $data as $k => $v ) {
983 if ( self
::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
985 } elseif ( is_array( $v ) ||
is_object( $v ) ) {
986 $data[$k] = self
::stripMetadata( $v );
990 $data = (object)$data;
997 * Remove metadata keys from a data array or object, non-recursive
999 * Note this removes all potential metadata keys, not just the defined
1003 * @param array|object $data
1004 * @param array &$metadata Store metadata here, if provided
1005 * @return array|object
1007 public static function stripMetadataNonRecursive( $data, &$metadata = null ) {
1008 if ( !is_array( $metadata ) ) {
1009 $metadata = array();
1011 if ( is_array( $data ) ||
is_object( $data ) ) {
1012 $isObj = is_object( $data );
1014 $data = (array)$data;
1016 $preserveKeys = isset( $data[self
::META_PRESERVE_KEYS
] )
1017 ?
(array)$data[self
::META_PRESERVE_KEYS
]
1019 foreach ( $data as $k => $v ) {
1020 if ( self
::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
1026 $data = (object)$data;
1033 * Get the 'real' size of a result item. This means the strlen() of the item,
1034 * or the sum of the strlen()s of the elements if the item is an array.
1035 * @note Once the deprecated public self::size is removed, we can rename this back to a less awkward name.
1036 * @param mixed $value
1039 private static function valueSize( $value ) {
1041 if ( is_array( $value ) ||
1042 is_object( $value ) && !is_callable( array( $value, '__toString' ) )
1044 foreach ( $value as $k => $v ) {
1045 if ( !self
::isMetadataKey( $s ) ) {
1046 $s +
= self
::valueSize( $v );
1049 } elseif ( is_scalar( $value ) ) {
1050 $s = strlen( $value );
1057 * Return a reference to the internal data at $path
1059 * @param array|string|null $path
1060 * @param string $create
1061 * If 'append', append empty arrays.
1062 * If 'prepend', prepend empty arrays.
1063 * If 'dummy', return a dummy array.
1064 * Else, raise an error.
1067 private function &path( $path, $create = 'append' ) {
1068 $path = (array)$path;
1069 $ret = &$this->data
;
1070 foreach ( $path as $i => $k ) {
1071 if ( !isset( $ret[$k] ) ) {
1072 switch ( $create ) {
1077 $ret = array( $k => array() ) +
$ret;
1083 $fail = join( '.', array_slice( $path, 0, $i +
1 ) );
1084 throw new InvalidArgumentException( "Path $fail does not exist" );
1087 if ( !is_array( $ret[$k] ) ) {
1088 $fail = join( '.', array_slice( $path, 0, $i +
1 ) );
1089 throw new InvalidArgumentException( "Path $fail is not an array" );
1098 /************************************************************************//**
1104 * Call this function when special elements such as '_element'
1105 * are needed by the formatter, for example in XML printing.
1106 * @deprecated since 1.25, you shouldn't have been using it in the first place
1107 * @since 1.23 $flag parameter added
1108 * @param bool $flag Set the raw mode flag to this state
1110 public function setRawMode( $flag = true ) {
1111 // Can't wfDeprecated() here, since we need to set this flag from
1112 // ApiMain for BC with stuff using self::getIsRawMode as
1113 // "self::getIsXMLMode".
1114 $this->isRawMode
= $flag;
1118 * Returns true whether the formatter requested raw data.
1119 * @deprecated since 1.25, you shouldn't have been using it in the first place
1122 public function getIsRawMode() {
1123 /// @todo: After Wikibase stops calling this, warn
1124 return $this->isRawMode
;
1128 * Get the result's internal data array (read-only)
1129 * @deprecated since 1.25, use $this->getResultData() instead
1132 public function getData() {
1133 /// @todo: Warn after fixing remaining callers: Wikibase, Gather
1134 return $this->getResultData( null, array(
1137 'Strip' => $this->isRawMode ?
'bc' : 'all',
1142 * Disable size checking in addValue(). Don't use this unless you
1143 * REALLY know what you're doing. Values added while size checking
1144 * was disabled will not be counted (ever)
1145 * @deprecated since 1.24, use ApiResult::NO_SIZE_CHECK
1147 public function disableSizeCheck() {
1148 wfDeprecated( __METHOD__
, '1.24' );
1149 $this->checkingSize
= false;
1153 * Re-enable size checking in addValue()
1154 * @deprecated since 1.24, use ApiResult::NO_SIZE_CHECK
1156 public function enableSizeCheck() {
1157 wfDeprecated( __METHOD__
, '1.24' );
1158 $this->checkingSize
= true;
1162 * Alias for self::setValue()
1164 * @since 1.21 int $flags replaced boolean $override
1165 * @deprecated since 1.25, use self::setValue() instead
1166 * @param array $arr To add $value to
1167 * @param string $name Index of $arr to add $value at
1168 * @param mixed $value
1169 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
1170 * This parameter used to be boolean, and the value of OVERRIDE=1 was
1171 * specifically chosen so that it would be backwards compatible with the
1172 * new method signature.
1174 public static function setElement( &$arr, $name, $value, $flags = 0 ) {
1175 /// @todo: Warn after fixing remaining callers: Wikibase
1176 return self
::setValue( $arr, $name, $value, $flags );
1180 * Adds a content element to an array.
1181 * Use this function instead of hardcoding the '*' element.
1182 * @deprecated since 1.25, use self::setContentValue() instead
1183 * @param array $arr To add the content element to
1184 * @param mixed $value
1185 * @param string $subElemName When present, content element is created
1186 * as a sub item of $arr. Use this parameter to create elements in
1187 * format "<elem>text</elem>" without attributes.
1189 public static function setContent( &$arr, $value, $subElemName = null ) {
1190 /// @todo: Warn after fixing remaining callers: Wikibase
1191 if ( is_array( $value ) ) {
1192 throw new InvalidArgumentException( __METHOD__
. ': Bad parameter' );
1194 if ( is_null( $subElemName ) ) {
1195 self
::setContentValue( $arr, 'content', $value );
1197 if ( !isset( $arr[$subElemName] ) ) {
1198 $arr[$subElemName] = array();
1200 self
::setContentValue( $arr[$subElemName], 'content', $value );
1205 * Set indexed tag name on all subarrays of $arr
1207 * Does not set the tag name for $arr itself.
1209 * @deprecated since 1.25, use self::setIndexedTagNameRecursive() instead
1211 * @param string $tag Tag name
1213 public function setIndexedTagName_recursive( &$arr, $tag ) {
1214 /// @todo: Warn after fixing remaining callers: Wikibase
1215 if ( !is_array( $arr ) ) {
1218 self
::setIndexedTagNameOnSubarrays( $arr, $tag );
1222 * Set indexed tag name on all subarrays of $arr
1224 * Does not set the tag name for $arr itself.
1227 * @deprecated For backwards compatibility, do not use
1228 * @todo: Remove after updating callers to use self::setIndexedTagNameRecursive
1229 * @param array &$arr
1230 * @param string $tag Tag name
1232 public static function setIndexedTagNameOnSubarrays( array &$arr, $tag ) {
1233 if ( !is_string( $tag ) ) {
1234 throw new InvalidArgumentException( 'Bad tag name' );
1236 foreach ( $arr as $k => &$v ) {
1237 if ( !self
::isMetadataKey( $k ) && is_array( $v ) ) {
1238 $v[self
::META_INDEXED_TAG_NAME
] = $tag;
1239 self
::setIndexedTagNameOnSubarrays( $v, $tag );
1245 * Alias for self::defineIndexedTagName()
1246 * @deprecated since 1.25, use $this->addIndexedTagName() instead
1247 * @param array $path Path to the array, like addValue()'s $path
1248 * @param string $tag
1250 public function setIndexedTagName_internal( $path, $tag ) {
1251 /// @todo: Warn after fixing remaining callers: Wikibase, Gather
1252 $this->addIndexedTagName( $path, $tag );
1256 * Alias for self::addParsedLimit()
1257 * @deprecated since 1.25, use $this->addParsedLimit() instead
1258 * @param string $moduleName
1261 public function setParsedLimit( $moduleName, $limit ) {
1262 wfDeprecated( __METHOD__
, '1.25' );
1263 $this->addParsedLimit( $moduleName, $limit );
1267 * Set the ApiMain for use by $this->beginContinuation()
1269 * @deprecated for backwards compatibility only, do not use
1270 * @param ApiMain $main
1272 public function setMainForContinuation( ApiMain
$main ) {
1273 $this->mainForContinuation
= $main;
1277 * Parse a 'continue' parameter and return status information.
1279 * This must be balanced by a call to endContinuation().
1282 * @deprecated since 1.25, use ApiContinuationManager instead
1283 * @param string|null $continue
1284 * @param ApiBase[] $allModules
1285 * @param array $generatedModules
1288 public function beginContinuation(
1289 $continue, array $allModules = array(), array $generatedModules = array()
1291 /// @todo: Warn after fixing remaining callers: Gather
1292 if ( $this->mainForContinuation
->getContinuationManager() ) {
1293 throw new UnexpectedValueException(
1294 __METHOD__
. ': Continuation already in progress from ' .
1295 $this->mainForContinuation
->getContinuationManager()->getSource()
1299 // Ugh. If $continue doesn't match that in the request, temporarily
1300 // replace the request when creating the ApiContinuationManager.
1301 if ( $continue === null ) {
1304 if ( $this->mainForContinuation
->getVal( 'continue', '' ) !== $continue ) {
1305 $oldCtx = $this->mainForContinuation
->getContext();
1306 $newCtx = new DerivativeContext( $oldCtx );
1307 $newCtx->setRequest( new DerivativeRequest(
1308 $oldCtx->getRequest(),
1309 array( 'continue' => $continue ) +
$oldCtx->getRequest()->getValues(),
1310 $oldCtx->getRequest()->wasPosted()
1312 $this->mainForContinuation
->setContext( $newCtx );
1313 $reset = new ScopedCallback(
1314 array( $this->mainForContinuation
, 'setContext' ),
1318 $manager = new ApiContinuationManager(
1319 $this->mainForContinuation
, $allModules, $generatedModules
1323 $this->mainForContinuation
->setContinuationManager( $manager );
1326 $manager->isGeneratorDone(),
1327 $manager->getRunModules(),
1333 * @deprecated since 1.25, use ApiContinuationManager instead
1334 * @param ApiBase $module
1335 * @param string $paramName
1336 * @param string|array $paramValue
1338 public function setContinueParam( ApiBase
$module, $paramName, $paramValue ) {
1339 wfDeprecated( __METHOD__
, '1.25' );
1340 if ( $this->mainForContinuation
->getContinuationManager() ) {
1341 $this->mainForContinuation
->getContinuationManager()->addContinueParam(
1342 $module, $paramName, $paramValue
1349 * @deprecated since 1.25, use ApiContinuationManager instead
1350 * @param ApiBase $module
1351 * @param string $paramName
1352 * @param string|array $paramValue
1354 public function setGeneratorContinueParam( ApiBase
$module, $paramName, $paramValue ) {
1355 wfDeprecated( __METHOD__
, '1.25' );
1356 if ( $this->mainForContinuation
->getContinuationManager() ) {
1357 $this->mainForContinuation
->getContinuationManager()->addGeneratorContinueParam(
1358 $module, $paramName, $paramValue
1364 * Close continuation, writing the data into the result
1366 * @deprecated since 1.25, use ApiContinuationManager instead
1367 * @param string $style 'standard' for the new style since 1.21, 'raw' for
1368 * the style used in 1.20 and earlier.
1370 public function endContinuation( $style = 'standard' ) {
1371 /// @todo: Warn after fixing remaining callers: Gather
1372 if ( !$this->mainForContinuation
->getContinuationManager() ) {
1376 if ( $style === 'raw' ) {
1377 $data = $this->mainForContinuation
->getContinuationManager()->getRawContinuation();
1379 $this->addValue( null, 'query-continue', $data, self
::ADD_ON_TOP | self
::NO_SIZE_CHECK
);
1382 $this->mainForContinuation
->getContinuationManager()->setContinuationIntoResult( $this );
1387 * No-op, this is now checked on insert.
1388 * @deprecated since 1.25
1390 public function cleanUpUTF8() {
1391 wfDeprecated( __METHOD__
, '1.25' );
1395 * Get the 'real' size of a result item. This means the strlen() of the item,
1396 * or the sum of the strlen()s of the elements if the item is an array.
1397 * @deprecated since 1.25, no external users known and there doesn't seem
1398 * to be any case for such use over just checking the return value from the
1400 * @param mixed $value
1403 public static function size( $value ) {
1404 wfDeprecated( __METHOD__
, '1.25' );
1405 return self
::valueSize( $value );
1409 * Converts a Status object to an array suitable for addValue
1410 * @deprecated since 1.25, use ApiErrorFormatter::arrayFromStatus()
1411 * @param Status $status
1412 * @param string $errorType
1415 public function convertStatusToArray( $status, $errorType = 'error' ) {
1416 /// @todo: Warn after fixing remaining callers: CentralAuth
1417 return $this->errorFormatter
->arrayFromStatus( $status, $errorType );
1421 * Alias for self::addIndexedTagName
1423 * A bunch of extensions were updated for an earlier version of this
1424 * extension which used this name.
1425 * @deprecated For backwards compatibility, do not use
1426 * @todo: Remove after updating callers to use self::addIndexedTagName
1428 public function defineIndexedTagName( $path, $tag ) {
1429 return $this->addIndexedTagName( $path, $tag );
1433 * Alias for self::stripMetadata
1435 * A bunch of extensions were updated for an earlier version of this
1436 * extension which used this name.
1437 * @deprecated For backwards compatibility, do not use
1438 * @todo: Remove after updating callers to use self::stripMetadata
1440 public static function removeMetadata( $data ) {
1441 return self
::stripMetadata( $data );
1445 * Alias for self::stripMetadataNonRecursive
1447 * A bunch of extensions were updated for an earlier version of this
1448 * extension which used this name.
1449 * @deprecated For backwards compatibility, do not use
1450 * @todo: Remove after updating callers to use self::stripMetadataNonRecursive
1452 public static function removeMetadataNonRecursive( $data, &$metadata = null ) {
1453 return self
::stripMetadataNonRecursive( $data, $metadata );
1457 * @deprecated For backwards compatibility, do not use
1458 * @todo: Remove after updating callers
1460 public static function transformForBC( array $data ) {
1461 return self
::applyTransformations( $data, array(
1467 * @deprecated For backwards compatibility, do not use
1468 * @todo: Remove after updating callers
1470 public static function transformForTypes( $data, $options = array() ) {
1471 $transforms = array(
1474 if ( isset( $options['assocAsObject'] ) ) {
1475 $transforms['Types']['AssocAsObject'] = $options['assocAsObject'];
1477 if ( isset( $options['armorKVP'] ) ) {
1478 $transforms['Types']['ArmorKVP'] = $options['armorKVP'];
1480 if ( !empty( $options['BC'] ) ) {
1481 $transforms['BC'] = array( 'nobool', 'no*', 'nosub' );
1483 return self
::applyTransformations( $data, $transforms );
1490 * For really cool vim folding this needs to be at the end:
1491 * vim: foldmarker=@{,@} foldmethod=marker