149 private $errorFormatter;
155 $this->maxSize = $maxSize;
164 $this->errorFormatter = $formatter;
185 self::META_TYPE =>
'assoc',
246 return self::applyTransformations( $this->data, $transforms );
249 $last = array_pop(
$path );
250 $ret = &$this->path(
$path,
'dummy' );
251 if ( !isset( $ret[$last] ) ) {
253 } elseif ( is_array( $ret[$last] ) ) {
254 return self::applyTransformations( $ret[$last], $transforms );
280 public static function setValue( array &$arr, $name, $value, $flags = 0 ) {
281 if ( ( $flags & self::NO_VALIDATE ) !== self::NO_VALIDATE ) {
282 $value = self::validateValue( $value );
285 if ( $name ===
null ) {
286 if ( $flags & self::ADD_ON_TOP ) {
287 array_unshift( $arr, $value );
294 $exists = isset( $arr[$name] );
295 if ( !$exists || ( $flags & self::OVERRIDE ) ) {
296 if ( !$exists && ( $flags & self::ADD_ON_TOP ) ) {
297 $arr = [ $name => $value ] + $arr;
299 $arr[$name] = $value;
301 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
302 $conflicts = array_intersect_key( $arr[$name], $value );
304 $arr[$name] += $value;
306 $keys = implode(
', ', array_keys( $conflicts ) );
307 throw new RuntimeException(
308 "Conflicting keys ($keys) when attempting to merge element $name"
311 } elseif ( $value !== $arr[$name] ) {
312 throw new RuntimeException(
313 "Attempting to add element $name=$value, existing value is {$arr[$name]}"
323 private static function validateValue( $value ) {
324 if ( is_object( $value ) ) {
327 if ( is_callable( [ $value,
'serializeForApiResult' ] ) ) {
329 $value = $value->serializeForApiResult();
330 if ( is_object( $value ) ) {
331 throw new UnexpectedValueException(
332 get_class( $oldValue ) .
'::serializeForApiResult() returned an object of class ' .
340 return self::validateValue( $value );
341 }
catch ( Exception $ex ) {
342 throw new UnexpectedValueException(
343 get_class( $oldValue ) .
'::serializeForApiResult() returned an invalid value: ' .
349 } elseif ( is_callable( [ $value,
'__toString' ] ) ) {
350 $value = (string)$value;
352 $value = (array)$value + [ self::META_TYPE =>
'assoc' ];
356 if ( is_string( $value ) ) {
358 static $contentLanguage =
null;
359 if ( !$contentLanguage ) {
360 $contentLanguage = MediaWikiServices::getInstance()->getContentLanguage();
362 $value = $contentLanguage->normalize( $value );
363 } elseif ( is_array( $value ) ) {
364 foreach ( $value as $k => $v ) {
365 $value[$k] = self::validateValue( $v );
367 } elseif ( $value !==
null && !is_scalar( $value ) ) {
368 $type = gettype( $value );
370 if ( is_resource( $value ) ) {
371 $type .=
'(' . get_resource_type( $value ) .
')';
373 throw new InvalidArgumentException(
"Cannot add $type to ApiResult" );
374 } elseif ( is_float( $value ) && !is_finite( $value ) ) {
375 throw new InvalidArgumentException(
'Cannot add non-finite floats to ApiResult' );
398 $arr = &$this->path(
$path, ( $flags & self::ADD_ON_TOP ) ?
'prepend' :
'append' );
400 if ( !( $flags & self::NO_SIZE_CHECK ) ) {
403 $value = self::validateValue( $value );
404 $flags |= self::NO_VALIDATE;
406 $newsize = $this->size + self::size( $value );
407 if ( $this->maxSize !==
false && $newsize > $this->maxSize ) {
408 $this->errorFormatter->addWarning(
409 'result', [
'apiwarn-truncatedresult', Message::numParam( $this->maxSize ) ]
413 $this->size = $newsize;
416 self::setValue( $arr, $name, $value, $flags );
428 if ( isset( $arr[$name] ) ) {
430 unset( $arr[$name] );
447 if ( $name ===
null ) {
449 throw new InvalidArgumentException(
'Cannot remove the data root' );
451 $name = array_pop(
$path );
453 $ret = self::unsetValue( $this->path(
$path,
'dummy' ), $name );
454 if ( !( $flags & self::NO_SIZE_CHECK ) ) {
455 $newsize = $this->size - self::size( $ret );
456 $this->size = max( $newsize, 0 );
471 if ( $name ===
null ) {
472 throw new InvalidArgumentException(
'Content value must be named' );
474 self::setContentField( $arr, $name, $flags );
475 self::setValue( $arr, $name, $value, $flags );
489 if ( $name ===
null ) {
490 throw new InvalidArgumentException(
'Content value must be named' );
505 $this->
addValue(
'limits', $moduleName, $limit,
506 self::OVERRIDE | self::NO_SIZE_CHECK );
524 if ( isset( $arr[self::META_CONTENT] ) &&
525 isset( $arr[$arr[self::META_CONTENT]] ) &&
526 !( $flags & self::OVERRIDE )
528 throw new RuntimeException(
529 "Attempting to set content element as $name when " . $arr[self::META_CONTENT] .
530 ' is already set as the content element'
533 $arr[self::META_CONTENT] = $name;
545 $arr = &$this->path(
$path, ( $flags & self::ADD_ON_TOP ) ?
'prepend' :
'append' );
546 self::setContentField( $arr, $name, $flags );
557 if ( !isset( $arr[self::META_SUBELEMENTS] ) ) {
558 $arr[self::META_SUBELEMENTS] = (array)$names;
560 $arr[self::META_SUBELEMENTS] = array_merge( $arr[self::META_SUBELEMENTS], (array)$names );
572 $arr = &$this->path(
$path );
573 self::setSubelementsList( $arr, $names );
584 if ( isset( $arr[self::META_SUBELEMENTS] ) ) {
585 $arr[self::META_SUBELEMENTS] = array_diff( $arr[self::META_SUBELEMENTS], (array)$names );
597 $arr = &$this->path(
$path );
598 self::unsetSubelementsList( $arr, $names );
608 if ( !is_string( $tag ) ) {
609 throw new InvalidArgumentException(
'Bad tag name' );
611 $arr[self::META_INDEXED_TAG_NAME] = $tag;
621 $arr = &$this->path(
$path );
622 self::setIndexedTagName( $arr, $tag );
633 if ( !is_string( $tag ) ) {
634 throw new InvalidArgumentException(
'Bad tag name' );
636 $arr[self::META_INDEXED_TAG_NAME] = $tag;
637 foreach ( $arr as $k => &$v ) {
638 if ( is_array( $v ) && !self::isMetadataKey( $k ) ) {
639 self::setIndexedTagNameRecursive( $v, $tag );
652 $arr = &$this->path(
$path );
653 self::setIndexedTagNameRecursive( $arr, $tag );
667 if ( !isset( $arr[self::META_PRESERVE_KEYS] ) ) {
668 $arr[self::META_PRESERVE_KEYS] = (array)$names;
670 $arr[self::META_PRESERVE_KEYS] = array_merge( $arr[self::META_PRESERVE_KEYS], (array)$names );
682 $arr = &$this->path(
$path );
683 self::setPreserveKeysList( $arr, $names );
694 if ( isset( $arr[self::META_PRESERVE_KEYS] ) ) {
695 $arr[self::META_PRESERVE_KEYS] = array_diff( $arr[self::META_PRESERVE_KEYS], (array)$names );
707 $arr = &$this->path(
$path );
708 self::unsetPreserveKeysList( $arr, $names );
719 public static function setArrayType( array &$arr, $type, $kvpKeyName =
null ) {
720 if ( !in_array( $type, [
721 'default',
'array',
'assoc',
'kvp',
'BCarray',
'BCassoc',
'BCkvp'
723 throw new InvalidArgumentException(
'Bad type' );
725 $arr[self::META_TYPE] = $type;
726 if ( is_string( $kvpKeyName ) ) {
727 $arr[self::META_KVP_KEY_NAME] = $kvpKeyName;
739 $arr = &$this->path(
$path );
740 self::setArrayType( $arr, $tag, $kvpKeyName );
751 self::setArrayType( $arr, $type, $kvpKeyName );
752 foreach ( $arr as $k => &$v ) {
753 if ( is_array( $v ) && !self::isMetadataKey( $k ) ) {
754 self::setArrayTypeRecursive( $v, $type, $kvpKeyName );
767 $arr = &$this->path(
$path );
768 self::setArrayTypeRecursive( $arr, $tag, $kvpKeyName );
787 return ord( $key ) === 95;
800 $strip = $transforms[
'Strip'] ??
'none';
801 if ( $strip ===
'base' ) {
802 $transforms[
'Strip'] =
'none';
804 $transformTypes = $transforms[
'Types'] ??
null;
805 if ( $transformTypes !==
null && !is_array( $transformTypes ) ) {
806 throw new InvalidArgumentException( __METHOD__ .
':Value for "Types" must be an array' );
810 $data = self::stripMetadataNonRecursive( $dataIn, $metadata );
812 if ( isset( $transforms[
'Custom'] ) ) {
813 if ( !is_callable( $transforms[
'Custom'] ) ) {
814 throw new InvalidArgumentException( __METHOD__ .
': Value for "Custom" must be callable' );
816 call_user_func_array( $transforms[
'Custom'], [ &$data, &$metadata ] );
819 if ( ( isset( $transforms[
'BC'] ) || $transformTypes !==
null ) &&
820 isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] ===
'BCkvp' &&
821 !isset( $metadata[self::META_KVP_KEY_NAME] )
823 throw new UnexpectedValueException(
'Type "BCkvp" used without setting ' .
824 'ApiResult::META_KVP_KEY_NAME metadata item' );
829 if ( isset( $transforms[
'BC'] ) ) {
830 if ( !is_array( $transforms[
'BC'] ) ) {
831 throw new InvalidArgumentException( __METHOD__ .
':Value for "BC" must be an array' );
833 if ( !in_array(
'nobool', $transforms[
'BC'],
true ) ) {
834 $boolKeys = isset( $metadata[self::META_BC_BOOLS] )
835 ? array_fill_keys( $metadata[self::META_BC_BOOLS],
true )
839 if ( !in_array(
'no*', $transforms[
'BC'],
true ) &&
840 isset( $metadata[self::META_CONTENT] ) && $metadata[self::META_CONTENT] !==
'*'
842 $k = $metadata[self::META_CONTENT];
843 $data[
'*'] = $data[$k];
845 $metadata[self::META_CONTENT] =
'*';
848 if ( !in_array(
'nosub', $transforms[
'BC'],
true ) &&
849 isset( $metadata[self::META_BC_SUBELEMENTS] )
851 foreach ( $metadata[self::META_BC_SUBELEMENTS] as $k ) {
852 if ( isset( $data[$k] ) ) {
855 self::META_CONTENT =>
'*',
856 self::META_TYPE =>
'assoc',
862 if ( isset( $metadata[self::META_TYPE] ) ) {
863 switch ( $metadata[self::META_TYPE] ) {
866 $metadata[self::META_TYPE] =
'default';
869 $transformTypes[
'ArmorKVP'] = $metadata[self::META_KVP_KEY_NAME];
876 $defaultType =
'array';
878 foreach ( $data as $k => &$v ) {
879 $v = is_array( $v ) ? self::applyTransformations( $v, $transforms ) : $v;
880 if ( $boolKeys !==
null && is_bool( $v ) && !isset( $boolKeys[$k] ) ) {
887 if ( is_string( $k ) ) {
888 $defaultType =
'assoc';
889 } elseif ( $k > $maxKey ) {
902 $keepMetadata = &$metadata;
906 $keepMetadata = array_intersect_key( $metadata, [
907 self::META_INDEXED_TAG_NAME => 1,
908 self::META_SUBELEMENTS => 1,
912 throw new InvalidArgumentException( __METHOD__ .
': Unknown value for "Strip"' );
916 if ( $transformTypes ===
null ) {
917 return $data + $keepMetadata;
920 if ( $defaultType ===
'array' && $maxKey !== count( $data ) - 1 ) {
921 $defaultType =
'assoc';
925 $type = $defaultType;
926 if ( isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] !==
'default' ) {
927 $type = $metadata[self::META_TYPE];
929 if ( ( $type ===
'kvp' || $type ===
'BCkvp' ) &&
930 empty( $transformTypes[
'ArmorKVP'] )
933 } elseif ( $type ===
'BCarray' ) {
935 } elseif ( $type ===
'BCassoc' ) {
942 $metadata[self::META_TYPE] =
'assoc';
943 $data += $keepMetadata;
944 return empty( $transformTypes[
'AssocAsObject'] ) ? $data : (object)$data;
956 uksort( $data,
static function ( $a, $b ):
int {
962 if ( is_numeric( trim( $a ) ) xor is_numeric( trim( $b ) ) ) {
963 return (
string)$a <=> (
string)$b;
969 $data = array_values( $data );
970 $metadata[self::META_TYPE] =
'array';
972 return $data + $keepMetadata;
976 $key = $metadata[self::META_KVP_KEY_NAME] ?? $transformTypes[
'ArmorKVP'];
977 $valKey = isset( $transforms[
'BC'] ) ?
'*' :
'value';
978 $assocAsObject = !empty( $transformTypes[
'AssocAsObject'] );
979 $merge = !empty( $metadata[self::META_KVP_MERGE] );
982 foreach ( $data as $k => $v ) {
983 if ( $merge && ( is_array( $v ) || is_object( $v ) ) ) {
985 if ( isset( $vArr[self::META_TYPE] ) ) {
986 $mergeType = $vArr[self::META_TYPE];
987 } elseif ( is_object( $v ) ) {
988 $mergeType =
'assoc';
990 $keys = array_keys( $vArr );
991 sort( $keys, SORT_NUMERIC );
992 $mergeType = ( $keys === array_keys( $keys ) ) ?
'array' :
'assoc';
997 if ( $mergeType ===
'assoc' ) {
1002 if ( $strip ===
'none' ) {
1003 self::setPreserveKeysList( $item, [ $key ] );
1010 if ( $strip ===
'none' ) {
1012 self::META_PRESERVE_KEYS => [ $key ],
1013 self::META_CONTENT => $valKey,
1014 self::META_TYPE =>
'assoc',
1018 $ret[] = $assocAsObject ? (object)$item : $item;
1020 $metadata[self::META_TYPE] =
'array';
1023 return $ret + $keepMetadata;
1026 throw new UnexpectedValueException(
"Unknown type '$type'" );
1041 if ( is_array( $data ) || is_object( $data ) ) {
1042 $isObj = is_object( $data );
1044 $data = (array)$data;
1046 $preserveKeys = isset( $data[self::META_PRESERVE_KEYS] )
1047 ? (array)$data[self::META_PRESERVE_KEYS]
1049 foreach ( $data as $k => $v ) {
1050 if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys,
true ) ) {
1052 } elseif ( is_array( $v ) || is_object( $v ) ) {
1053 $data[$k] = self::stripMetadata( $v );
1057 $data = (object)$data;
1075 if ( !is_array( $metadata ) ) {
1078 if ( is_array( $data ) || is_object( $data ) ) {
1079 $isObj = is_object( $data );
1081 $data = (array)$data;
1083 $preserveKeys = isset( $data[self::META_PRESERVE_KEYS] )
1084 ? (array)$data[self::META_PRESERVE_KEYS]
1086 foreach ( $data as $k => $v ) {
1087 if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys,
true ) ) {
1093 $data = (object)$data;
1105 private static function size( $value ) {
1107 if ( is_array( $value ) ) {
1108 foreach ( $value as $k => $v ) {
1109 if ( !self::isMetadataKey( $k ) ) {
1110 $s += self::size( $v );
1113 } elseif ( is_scalar( $value ) ) {
1114 $s = strlen( $value );
1131 private function &path(
$path, $create =
'append' ) {
1133 $ret = &$this->data;
1134 foreach (
$path as $i => $k ) {
1135 if ( !isset( $ret[$k] ) ) {
1136 switch ( $create ) {
1141 $ret = [ $k => [] ] + $ret;
1147 $fail = implode(
'.', array_slice(
$path, 0, $i + 1 ) );
1148 throw new InvalidArgumentException(
"Path $fail does not exist" );
1151 if ( !is_array( $ret[$k] ) ) {
1152 $fail = implode(
'.', array_slice(
$path, 0, $i + 1 ) );
1153 throw new InvalidArgumentException(
"Path $fail is not an array" );
1173 foreach ( $vars as $k => $v ) {
1174 if ( is_array( $v ) || is_object( $v ) ) {
1175 $vars[$k] = self::addMetadataToResultVars( (array)$v, is_object( $v ) );
1176 } elseif ( is_bool( $v ) ) {
1180 if ( is_string( $k ) ) {
1182 } elseif ( $k > $maxKey ) {
1186 if ( !$hash && $maxKey !== count( $vars ) - 1 ) {
1194 $keys = array_diff( array_keys( $vars ), [
1195 self::META_TYPE, self::META_PRESERVE_KEYS, self::META_KVP_KEY_NAME,
1196 self::META_INDEXED_TAG_NAME, self::META_BC_BOOLS
1200 self::META_TYPE =>
'kvp',
1201 self::META_KVP_KEY_NAME =>
'key',
1202 self::META_PRESERVE_KEYS => $keys,
1203 self::META_BC_BOOLS => $bools,
1204 self::META_INDEXED_TAG_NAME =>
'var',
1208 self::META_TYPE =>
'array',
1209 self::META_BC_BOOLS => $bools,
1210 self::META_INDEXED_TAG_NAME =>
'value',
1225 $dbInfinity ??= MediaWikiServices::getInstance()->getConnectionProvider()
1226 ->getReplicaDatabase()
1229 if ( $expiry ===
'' || $expiry ===
null || $expiry ===
false ||
wfIsInfinity( $str)
Determine input string is represents as infinity.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
This class represents the result of the API operations.
addArrayType( $path, $tag, $kvpKeyName=null)
Set the array data type for a path.
static unsetSubelementsList(array &$arr, $names)
Causes the elements with the specified names to be output as attributes (when possible) rather than a...
static unsetPreserveKeysList(array &$arr, $names)
Don't preserve specified keys.
static applyTransformations(array $dataIn, array $transforms)
Apply transformations to an array, returning the transformed array.
const META_TYPE
Key for the 'type' metadata item.
static stripMetadataNonRecursive( $data, &$metadata=null)
Remove metadata keys from a data array or object, non-recursive.
static setArrayType(array &$arr, $type, $kvpKeyName=null)
Set the array data type.
serializeForApiResult()
Allow for adding one ApiResult into another.
static addMetadataToResultVars( $vars, $forceHash=true)
Add the correct metadata to an array of vars we want to export through the API.
static setValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name.
const META_SUBELEMENTS
Key for the 'subelements' metadata item.
addIndexedTagName( $path, $tag)
Set the tag name for numeric-keyed values in XML format.
addValue( $path, $name, $value, $flags=0)
Add value to the output data at the given path.
const META_BC_BOOLS
Key for the 'BC bools' metadata item.
const META_PRESERVE_KEYS
Key for the 'preserve keys' metadata item.
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
addArrayTypeRecursive( $path, $tag, $kvpKeyName=null)
Set the array data type for a path recursively.
getSize()
Get the size of the result, i.e.
static unsetValue(array &$arr, $name)
Remove an output value to the array by name.
static setPreserveKeysList(array &$arr, $names)
Preserve specified keys.
addPreserveKeysList( $path, $names)
Preserve specified keys.
addParsedLimit( $moduleName, $limit)
Add the numeric limit for a limit=max to the result.
addSubelementsList( $path, $names)
Causes the elements with the specified names to be output as subelements rather than attributes.
static stripMetadata( $data)
Recursively remove metadata keys from a data array or object.
const META_CONTENT
Key for the 'content' metadata item.
addIndexedTagNameRecursive( $path, $tag)
Set indexed tag name on $path and all subarrays.
removeSubelementsList( $path, $names)
Causes the elements with the specified names to be output as attributes (when possible) rather than a...
setErrorFormatter(ApiErrorFormatter $formatter)
const OVERRIDE
Override existing value in addValue(), setValue(), and similar functions.
static setSubelementsList(array &$arr, $names)
Causes the elements with the specified names to be output as subelements rather than attributes.
static setArrayTypeRecursive(array &$arr, $type, $kvpKeyName=null)
Set the array data type recursively.
const META_KVP_KEY_NAME
Key for the metadata item whose value specifies the name used for the kvp key in the alternative outp...
removeValue( $path, $name, $flags=0)
Remove value from the output data at the given path.
const ADD_ON_TOP
For addValue(), setValue() and similar functions, if the value does not exist, add it as the first el...
getResultData( $path=[], $transforms=[])
Get the result data array.
const META_BC_SUBELEMENTS
Key for the 'BC subelements' metadata item.
removePreserveKeysList( $path, $names)
Don't preserve specified keys.
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
const META_INDEXED_TAG_NAME
Key for the 'indexed tag name' metadata item.
const META_KVP_MERGE
Key for the metadata item that indicates that the KVP key should be added into an assoc value,...
reset()
Clear the current result data.
static setContentValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name and mark as META_CONTENT.
static setIndexedTagNameRecursive(array &$arr, $tag)
Set indexed tag name on $arr and all subarrays.
static setContentField(array &$arr, $name, $flags=0)
Set the name of the content field name (META_CONTENT)
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
const NO_VALIDATE
For addValue(), setValue() and similar functions, do not validate data.
addContentValue( $path, $name, $value, $flags=0)
Add value to the output data at the given path and mark as META_CONTENT.
addContentField( $path, $name, $flags=0)
Set the name of the content field name (META_CONTENT)
static isMetadataKey( $key)
Test whether a key should be considered metadata.
This interface allows for overriding the default conversion applied by ApiResult::validateValue().