152 $this->maxSize = $maxSize;
162 $this->errorFormatter = $formatter;
184 self::META_TYPE =>
'assoc',
245 return self::applyTransformations( $this->data, $transforms );
248 $last = array_pop(
$path );
250 if ( !isset( $ret[$last] ) ) {
252 } elseif ( is_array( $ret[$last] ) ) {
253 return self::applyTransformations( $ret[$last], $transforms );
279 public static function setValue( array &$arr, $name, $value, $flags = 0 ) {
280 if ( ( $flags & self::NO_VALIDATE ) !== self::NO_VALIDATE ) {
281 $value = self::validateValue( $value );
284 if ( $name ===
null ) {
285 if ( $flags & self::ADD_ON_TOP ) {
286 array_unshift( $arr, $value );
288 array_push( $arr, $value );
293 $exists = isset( $arr[$name] );
294 if ( !$exists || ( $flags & self::OVERRIDE ) ) {
295 if ( !$exists && ( $flags & self::ADD_ON_TOP ) ) {
296 $arr = [ $name => $value ] + $arr;
298 $arr[$name] = $value;
300 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
301 $conflicts = array_intersect_key( $arr[$name], $value );
303 $arr[$name] += $value;
305 $keys = implode(
', ', array_keys( $conflicts ) );
306 throw new RuntimeException(
307 "Conflicting keys ($keys) when attempting to merge element $name"
311 throw new RuntimeException(
312 "Attempting to add element $name=$value, existing value is {$arr[$name]}"
323 if ( is_object( $value ) ) {
326 if ( is_callable( [ $value,
'serializeForApiResult' ] ) ) {
328 $value = $value->serializeForApiResult();
329 if ( is_object( $value ) ) {
330 throw new UnexpectedValueException(
331 get_class( $oldValue ) .
'::serializeForApiResult() returned an object of class ' .
339 return self::validateValue( $value );
340 }
catch ( Exception $ex ) {
341 throw new UnexpectedValueException(
342 get_class( $oldValue ) .
'::serializeForApiResult() returned an invalid value: ' .
348 } elseif ( is_callable( [ $value,
'__toString' ] ) ) {
349 $value = (string)$value;
351 $value = (array)$value + [ self::META_TYPE =>
'assoc' ];
354 if ( is_array( $value ) ) {
358 foreach ( $value as $k => $v ) {
359 $tmp[$k] = self::validateValue( $v );
362 } elseif ( is_float( $value ) && !is_finite( $value ) ) {
363 throw new InvalidArgumentException(
'Cannot add non-finite floats to ApiResult' );
364 } elseif ( is_string( $value ) ) {
365 $value = MediaWikiServices::getInstance()->getContentLanguage()->normalize( $value );
366 } elseif ( $value !==
null && !is_scalar( $value ) ) {
367 $type = gettype( $value );
369 if ( is_resource( $value ) ) {
370 $type .=
'(' . get_resource_type( $value ) .
')';
372 throw new InvalidArgumentException(
"Cannot add $type to ApiResult" );
395 $arr = &$this->
path(
$path, ( $flags & self::ADD_ON_TOP ) ?
'prepend' :
'append' );
397 if ( !( $flags & self::NO_SIZE_CHECK ) ) {
400 $value = self::validateValue( $value );
401 $flags |= self::NO_VALIDATE;
403 $newsize = $this->
size + self::size( $value );
404 if ( $this->maxSize !==
false && $newsize > $this->maxSize ) {
405 $this->errorFormatter->addWarning(
410 $this->
size = $newsize;
413 self::setValue( $arr, $name, $value, $flags );
425 if ( isset( $arr[$name] ) ) {
427 unset( $arr[$name] );
444 if ( $name ===
null ) {
446 throw new InvalidArgumentException(
'Cannot remove the data root' );
448 $name = array_pop(
$path );
450 $ret = self::unsetValue( $this->
path(
$path,
'dummy' ), $name );
451 if ( !( $flags & self::NO_SIZE_CHECK ) ) {
452 $newsize = $this->
size - self::size( $ret );
453 $this->
size = max( $newsize, 0 );
468 if ( $name ===
null ) {
469 throw new InvalidArgumentException(
'Content value must be named' );
471 self::setContentField( $arr, $name, $flags );
472 self::setValue( $arr, $name, $value, $flags );
486 if ( $name ===
null ) {
487 throw new InvalidArgumentException(
'Content value must be named' );
502 $this->
addValue(
'limits', $moduleName, $limit,
503 self::OVERRIDE | self::NO_SIZE_CHECK );
522 if ( isset( $arr[self::META_CONTENT] ) &&
523 isset( $arr[$arr[self::META_CONTENT]] ) &&
524 !( $flags & self::OVERRIDE )
526 throw new RuntimeException(
527 "Attempting to set content element as $name when " . $arr[self::META_CONTENT] .
528 ' is already set as the content element'
531 $arr[self::META_CONTENT] = $name;
543 $arr = &$this->
path(
$path, ( $flags & self::ADD_ON_TOP ) ?
'prepend' :
'append' );
544 self::setContentField( $arr, $name, $flags );
555 if ( !isset( $arr[self::META_SUBELEMENTS] ) ) {
556 $arr[self::META_SUBELEMENTS] = (array)$names;
558 $arr[self::META_SUBELEMENTS] = array_merge( $arr[self::META_SUBELEMENTS], (array)$names );
571 self::setSubelementsList( $arr, $names );
582 if ( isset( $arr[self::META_SUBELEMENTS] ) ) {
583 $arr[self::META_SUBELEMENTS] = array_diff( $arr[self::META_SUBELEMENTS], (array)$names );
596 self::unsetSubelementsList( $arr, $names );
606 if ( !is_string( $tag ) ) {
607 throw new InvalidArgumentException(
'Bad tag name' );
609 $arr[self::META_INDEXED_TAG_NAME] = $tag;
620 self::setIndexedTagName( $arr, $tag );
631 if ( !is_string( $tag ) ) {
632 throw new InvalidArgumentException(
'Bad tag name' );
634 $arr[self::META_INDEXED_TAG_NAME] = $tag;
635 foreach ( $arr as $k => &$v ) {
636 if ( !self::isMetadataKey( $k ) && is_array( $v ) ) {
637 self::setIndexedTagNameRecursive( $v, $tag );
651 self::setIndexedTagNameRecursive( $arr, $tag );
665 if ( !isset( $arr[self::META_PRESERVE_KEYS] ) ) {
666 $arr[self::META_PRESERVE_KEYS] = (array)$names;
668 $arr[self::META_PRESERVE_KEYS] = array_merge( $arr[self::META_PRESERVE_KEYS], (array)$names );
681 self::setPreserveKeysList( $arr, $names );
692 if ( isset( $arr[self::META_PRESERVE_KEYS] ) ) {
693 $arr[self::META_PRESERVE_KEYS] = array_diff( $arr[self::META_PRESERVE_KEYS], (array)$names );
706 self::unsetPreserveKeysList( $arr, $names );
718 if ( !in_array(
$type, [
719 'default',
'array',
'assoc',
'kvp',
'BCarray',
'BCassoc',
'BCkvp'
721 throw new InvalidArgumentException(
'Bad type' );
723 $arr[self::META_TYPE] =
$type;
724 if ( is_string( $kvpKeyName ) ) {
725 $arr[self::META_KVP_KEY_NAME] = $kvpKeyName;
738 self::setArrayType( $arr, $tag, $kvpKeyName );
749 self::setArrayType( $arr,
$type, $kvpKeyName );
750 foreach ( $arr as $k => &$v ) {
751 if ( !self::isMetadataKey( $k ) && is_array( $v ) ) {
752 self::setArrayTypeRecursive( $v,
$type, $kvpKeyName );
766 self::setArrayTypeRecursive( $arr, $tag, $kvpKeyName );
783 return substr( $key, 0, 1 ) ===
'_';
796 $strip = $transforms[
'Strip'] ??
'none';
797 if ( $strip ===
'base' ) {
798 $transforms[
'Strip'] =
'none';
800 $transformTypes = $transforms[
'Types'] ??
null;
801 if ( $transformTypes !==
null && !is_array( $transformTypes ) ) {
802 throw new InvalidArgumentException( __METHOD__ .
':Value for "Types" must be an array' );
806 $data = self::stripMetadataNonRecursive( $dataIn, $metadata );
808 if ( isset( $transforms[
'Custom'] ) ) {
809 if ( !is_callable( $transforms[
'Custom'] ) ) {
810 throw new InvalidArgumentException( __METHOD__ .
': Value for "Custom" must be callable' );
812 call_user_func_array( $transforms[
'Custom'], [ &
$data, &$metadata ] );
815 if ( ( isset( $transforms[
'BC'] ) || $transformTypes !==
null ) &&
816 isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] ===
'BCkvp' &&
817 !isset( $metadata[self::META_KVP_KEY_NAME] )
819 throw new UnexpectedValueException(
'Type "BCkvp" used without setting ' .
820 'ApiResult::META_KVP_KEY_NAME metadata item' );
825 if ( isset( $transforms[
'BC'] ) ) {
826 if ( !is_array( $transforms[
'BC'] ) ) {
827 throw new InvalidArgumentException( __METHOD__ .
':Value for "BC" must be an array' );
829 if ( !in_array(
'nobool', $transforms[
'BC'],
true ) ) {
830 $boolKeys = isset( $metadata[self::META_BC_BOOLS] )
831 ? array_flip( $metadata[self::META_BC_BOOLS] )
835 if ( !in_array(
'no*', $transforms[
'BC'],
true ) &&
836 isset( $metadata[self::META_CONTENT] ) && $metadata[self::META_CONTENT] !==
'*'
838 $k = $metadata[self::META_CONTENT];
841 $metadata[self::META_CONTENT] =
'*';
844 if ( !in_array(
'nosub', $transforms[
'BC'],
true ) &&
845 isset( $metadata[self::META_BC_SUBELEMENTS] )
847 foreach ( $metadata[self::META_BC_SUBELEMENTS] as $k ) {
848 if ( isset(
$data[$k] ) ) {
851 self::META_CONTENT =>
'*',
852 self::META_TYPE =>
'assoc',
858 if ( isset( $metadata[self::META_TYPE] ) ) {
859 switch ( $metadata[self::META_TYPE] ) {
862 $metadata[self::META_TYPE] =
'default';
865 $transformTypes[
'ArmorKVP'] = $metadata[self::META_KVP_KEY_NAME];
872 $defaultType =
'array';
874 foreach (
$data as $k => &$v ) {
875 $v = is_array( $v ) ? self::applyTransformations( $v, $transforms ) : $v;
876 if ( $boolKeys !==
null && is_bool( $v ) && !isset( $boolKeys[$k] ) ) {
883 if ( is_string( $k ) ) {
884 $defaultType =
'assoc';
885 } elseif ( $k > $maxKey ) {
898 $keepMetadata = &$metadata;
901 $keepMetadata = array_intersect_key( $metadata, [
902 self::META_INDEXED_TAG_NAME => 1,
903 self::META_SUBELEMENTS => 1,
907 throw new InvalidArgumentException( __METHOD__ .
': Unknown value for "Strip"' );
911 if ( $transformTypes !==
null ) {
912 if ( $defaultType ===
'array' && $maxKey !== count(
$data ) - 1 ) {
913 $defaultType =
'assoc';
917 $type = $defaultType;
918 if ( isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] !==
'default' ) {
919 $type = $metadata[self::META_TYPE];
921 if ( (
$type ===
'kvp' ||
$type ===
'BCkvp' ) &&
922 empty( $transformTypes[
'ArmorKVP'] )
925 } elseif (
$type ===
'BCarray' ) {
927 } elseif (
$type ===
'BCassoc' ) {
934 $metadata[self::META_TYPE] =
'assoc';
935 $data += $keepMetadata;
936 return empty( $transformTypes[
'AssocAsObject'] ) ?
$data : (object)
$data;
941 $metadata[self::META_TYPE] =
'array';
942 return $data + $keepMetadata;
946 $key = $metadata[self::META_KVP_KEY_NAME] ?? $transformTypes[
'ArmorKVP'];
947 $valKey = isset( $transforms[
'BC'] ) ?
'*' :
'value';
948 $assocAsObject = !empty( $transformTypes[
'AssocAsObject'] );
949 $merge = !empty( $metadata[self::META_KVP_MERGE] );
952 foreach (
$data as $k => $v ) {
953 if ( $merge && ( is_array( $v ) || is_object( $v ) ) ) {
955 if ( isset( $vArr[self::META_TYPE] ) ) {
956 $mergeType = $vArr[self::META_TYPE];
957 } elseif ( is_object( $v ) ) {
958 $mergeType =
'assoc';
960 $keys = array_keys( $vArr );
961 sort(
$keys, SORT_NUMERIC );
962 $mergeType = (
$keys === array_keys(
$keys ) ) ?
'array' :
'assoc';
967 if ( $mergeType ===
'assoc' ) {
971 if ( $strip ===
'none' ) {
972 self::setPreserveKeysList( $item, [ $key ] );
979 if ( $strip ===
'none' ) {
981 self::META_PRESERVE_KEYS => [ $key ],
982 self::META_CONTENT => $valKey,
983 self::META_TYPE =>
'assoc',
987 $ret[] = $assocAsObject ? (object)$item : $item;
989 $metadata[self::META_TYPE] =
'array';
991 return $ret + $keepMetadata;
994 throw new UnexpectedValueException(
"Unknown type '$type'" );
997 return $data + $keepMetadata;
1012 if ( is_array(
$data ) || is_object(
$data ) ) {
1013 $isObj = is_object(
$data );
1017 $preserveKeys = isset(
$data[self::META_PRESERVE_KEYS] )
1018 ? (array)
$data[self::META_PRESERVE_KEYS]
1020 foreach (
$data as $k => $v ) {
1021 if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys,
true ) ) {
1023 } elseif ( is_array( $v ) || is_object( $v ) ) {
1024 $data[$k] = self::stripMetadata( $v );
1046 if ( !is_array( $metadata ) ) {
1049 if ( is_array(
$data ) || is_object(
$data ) ) {
1050 $isObj = is_object(
$data );
1054 $preserveKeys = isset(
$data[self::META_PRESERVE_KEYS] )
1055 ? (array)
$data[self::META_PRESERVE_KEYS]
1057 foreach (
$data as $k => $v ) {
1058 if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys,
true ) ) {
1076 private static function size( $value ) {
1078 if ( is_array( $value ) ) {
1079 foreach ( $value as $k => $v ) {
1080 if ( !self::isMetadataKey( $k ) ) {
1081 $s += self::size( $v );
1084 } elseif ( is_scalar( $value ) ) {
1085 $s = strlen( $value );
1104 $ret = &$this->data;
1105 foreach (
$path as $i => $k ) {
1106 if ( !isset( $ret[$k] ) ) {
1107 switch ( $create ) {
1112 $ret = [ $k => [] ] + $ret;
1118 $fail = implode(
'.', array_slice(
$path, 0, $i + 1 ) );
1119 throw new InvalidArgumentException(
"Path $fail does not exist" );
1122 if ( !is_array( $ret[$k] ) ) {
1123 $fail = implode(
'.', array_slice(
$path, 0, $i + 1 ) );
1124 throw new InvalidArgumentException(
"Path $fail is not an array" );
1144 foreach ( $vars as $k => $v ) {
1145 if ( is_array( $v ) || is_object( $v ) ) {
1146 $vars[$k] = self::addMetadataToResultVars( (array)$v, is_object( $v ) );
1147 } elseif ( is_bool( $v ) ) {
1151 if ( is_string( $k ) ) {
1153 } elseif ( $k > $maxKey ) {
1157 if ( !$hash && $maxKey !== count( $vars ) - 1 ) {
1165 $keys = array_diff( array_keys( $vars ), [
1166 self::META_TYPE, self::META_PRESERVE_KEYS, self::META_KVP_KEY_NAME,
1167 self::META_INDEXED_TAG_NAME, self::META_BC_BOOLS
1171 self::META_TYPE =>
'kvp',
1172 self::META_KVP_KEY_NAME =>
'key',
1173 self::META_PRESERVE_KEYS =>
$keys,
1174 self::META_BC_BOOLS => $bools,
1175 self::META_INDEXED_TAG_NAME =>
'var',
1179 self::META_TYPE =>
'array',
1180 self::META_BC_BOOLS => $bools,
1181 self::META_INDEXED_TAG_NAME =>
'value',
1196 if ( $dbInfinity ===
null ) {
1200 if ( $expiry ===
'' || $expiry ===
null || $expiry ===
false ||
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
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.
static validateValue( $value)
Validate a value for addition to the result.
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)
Set the error formatter.
const OVERRIDE
Override existing value in addValue(), setValue(), and similar functions.
& path( $path, $create='append')
Return a reference to the internal data at $path.
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 size( $value)
Get the 'real' size of a result item.
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().