152 $this->maxSize = $maxSize;
161 $this->errorFormatter = $formatter;
182 self::META_TYPE =>
'assoc',
243 return self::applyTransformations( $this->data, $transforms );
246 $last = array_pop(
$path );
248 if ( !isset( $ret[$last] ) ) {
250 } elseif ( is_array( $ret[$last] ) ) {
251 return self::applyTransformations( $ret[$last], $transforms );
277 public static function setValue( array &$arr, $name, $value, $flags = 0 ) {
278 if ( ( $flags & self::NO_VALIDATE ) !== self::NO_VALIDATE ) {
279 $value = self::validateValue( $value );
282 if ( $name ===
null ) {
283 if ( $flags & self::ADD_ON_TOP ) {
284 array_unshift( $arr, $value );
286 array_push( $arr, $value );
291 $exists = isset( $arr[$name] );
292 if ( !$exists || ( $flags & self::OVERRIDE ) ) {
293 if ( !$exists && ( $flags & self::ADD_ON_TOP ) ) {
294 $arr = [ $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 = implode(
', ', array_keys( $conflicts ) );
304 throw new RuntimeException(
305 "Conflicting keys ($keys) when attempting to merge element $name"
308 } elseif ( $value !== $arr[$name] ) {
309 throw new RuntimeException(
310 "Attempting to add element $name=$value, existing value is {$arr[$name]}"
321 if ( is_object( $value ) ) {
324 if ( is_callable( [ $value,
'serializeForApiResult' ] ) ) {
326 $value = $value->serializeForApiResult();
327 if ( is_object( $value ) ) {
328 throw new UnexpectedValueException(
329 get_class( $oldValue ) .
'::serializeForApiResult() returned an object of class ' .
337 return self::validateValue( $value );
338 }
catch ( Exception $ex ) {
339 throw new UnexpectedValueException(
340 get_class( $oldValue ) .
'::serializeForApiResult() returned an invalid value: ' .
346 } elseif ( is_callable( [ $value,
'__toString' ] ) ) {
347 $value = (string)$value;
349 $value = (array)$value + [ self::META_TYPE =>
'assoc' ];
353 if ( is_string( $value ) ) {
355 static $contentLanguage =
null;
356 if ( !$contentLanguage ) {
357 $contentLanguage = MediaWikiServices::getInstance()->getContentLanguage();
359 $value = $contentLanguage->normalize( $value );
360 } elseif ( is_array( $value ) ) {
361 foreach ( $value as $k => $v ) {
362 $value[$k] = self::validateValue( $v );
364 } elseif ( $value !==
null && !is_scalar( $value ) ) {
365 $type = gettype( $value );
367 if ( is_resource( $value ) ) {
368 $type .=
'(' . get_resource_type( $value ) .
')';
370 throw new InvalidArgumentException(
"Cannot add $type to ApiResult" );
371 } elseif ( is_float( $value ) && !is_finite( $value ) ) {
372 throw new InvalidArgumentException(
'Cannot add non-finite floats 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 );
521 if ( isset( $arr[self::META_CONTENT] ) &&
522 isset( $arr[$arr[self::META_CONTENT]] ) &&
523 !( $flags & self::OVERRIDE )
525 throw new RuntimeException(
526 "Attempting to set content element as $name when " . $arr[self::META_CONTENT] .
527 ' is already set as the content element'
530 $arr[self::META_CONTENT] = $name;
542 $arr = &$this->
path(
$path, ( $flags & self::ADD_ON_TOP ) ?
'prepend' :
'append' );
543 self::setContentField( $arr, $name, $flags );
554 if ( !isset( $arr[self::META_SUBELEMENTS] ) ) {
555 $arr[self::META_SUBELEMENTS] = (array)$names;
557 $arr[self::META_SUBELEMENTS] = array_merge( $arr[self::META_SUBELEMENTS], (array)$names );
570 self::setSubelementsList( $arr, $names );
581 if ( isset( $arr[self::META_SUBELEMENTS] ) ) {
582 $arr[self::META_SUBELEMENTS] = array_diff( $arr[self::META_SUBELEMENTS], (array)$names );
595 self::unsetSubelementsList( $arr, $names );
605 if ( !is_string( $tag ) ) {
606 throw new InvalidArgumentException(
'Bad tag name' );
608 $arr[self::META_INDEXED_TAG_NAME] = $tag;
619 self::setIndexedTagName( $arr, $tag );
630 if ( !is_string( $tag ) ) {
631 throw new InvalidArgumentException(
'Bad tag name' );
633 $arr[self::META_INDEXED_TAG_NAME] = $tag;
634 foreach ( $arr as $k => &$v ) {
635 if ( is_array( $v ) && !self::isMetadataKey( $k ) ) {
636 self::setIndexedTagNameRecursive( $v, $tag );
650 self::setIndexedTagNameRecursive( $arr, $tag );
664 if ( !isset( $arr[self::META_PRESERVE_KEYS] ) ) {
665 $arr[self::META_PRESERVE_KEYS] = (array)$names;
667 $arr[self::META_PRESERVE_KEYS] = array_merge( $arr[self::META_PRESERVE_KEYS], (array)$names );
680 self::setPreserveKeysList( $arr, $names );
691 if ( isset( $arr[self::META_PRESERVE_KEYS] ) ) {
692 $arr[self::META_PRESERVE_KEYS] = array_diff( $arr[self::META_PRESERVE_KEYS], (array)$names );
705 self::unsetPreserveKeysList( $arr, $names );
717 if ( !in_array(
$type, [
718 'default',
'array',
'assoc',
'kvp',
'BCarray',
'BCassoc',
'BCkvp'
720 throw new InvalidArgumentException(
'Bad type' );
722 $arr[self::META_TYPE] =
$type;
723 if ( is_string( $kvpKeyName ) ) {
724 $arr[self::META_KVP_KEY_NAME] = $kvpKeyName;
737 self::setArrayType( $arr, $tag, $kvpKeyName );
748 self::setArrayType( $arr,
$type, $kvpKeyName );
749 foreach ( $arr as $k => &$v ) {
750 if ( is_array( $v ) && !self::isMetadataKey( $k ) ) {
751 self::setArrayTypeRecursive( $v,
$type, $kvpKeyName );
765 self::setArrayTypeRecursive( $arr, $tag, $kvpKeyName );
784 return ord( $key ) === 95;
797 $strip = $transforms[
'Strip'] ??
'none';
798 if ( $strip ===
'base' ) {
799 $transforms[
'Strip'] =
'none';
801 $transformTypes = $transforms[
'Types'] ??
null;
802 if ( $transformTypes !==
null && !is_array( $transformTypes ) ) {
803 throw new InvalidArgumentException( __METHOD__ .
':Value for "Types" must be an array' );
807 $data = self::stripMetadataNonRecursive( $dataIn, $metadata );
809 if ( isset( $transforms[
'Custom'] ) ) {
810 if ( !is_callable( $transforms[
'Custom'] ) ) {
811 throw new InvalidArgumentException( __METHOD__ .
': Value for "Custom" must be callable' );
813 call_user_func_array( $transforms[
'Custom'], [ &
$data, &$metadata ] );
816 if ( ( isset( $transforms[
'BC'] ) || $transformTypes !==
null ) &&
817 isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] ===
'BCkvp' &&
818 !isset( $metadata[self::META_KVP_KEY_NAME] )
820 throw new UnexpectedValueException(
'Type "BCkvp" used without setting ' .
821 'ApiResult::META_KVP_KEY_NAME metadata item' );
826 if ( isset( $transforms[
'BC'] ) ) {
827 if ( !is_array( $transforms[
'BC'] ) ) {
828 throw new InvalidArgumentException( __METHOD__ .
':Value for "BC" must be an array' );
830 if ( !in_array(
'nobool', $transforms[
'BC'],
true ) ) {
831 $boolKeys = isset( $metadata[self::META_BC_BOOLS] )
832 ? array_fill_keys( $metadata[self::META_BC_BOOLS],
true )
836 if ( !in_array(
'no*', $transforms[
'BC'],
true ) &&
837 isset( $metadata[self::META_CONTENT] ) && $metadata[self::META_CONTENT] !==
'*'
839 $k = $metadata[self::META_CONTENT];
842 $metadata[self::META_CONTENT] =
'*';
845 if ( !in_array(
'nosub', $transforms[
'BC'],
true ) &&
846 isset( $metadata[self::META_BC_SUBELEMENTS] )
848 foreach ( $metadata[self::META_BC_SUBELEMENTS] as $k ) {
849 if ( isset(
$data[$k] ) ) {
852 self::META_CONTENT =>
'*',
853 self::META_TYPE =>
'assoc',
859 if ( isset( $metadata[self::META_TYPE] ) ) {
860 switch ( $metadata[self::META_TYPE] ) {
863 $metadata[self::META_TYPE] =
'default';
866 $transformTypes[
'ArmorKVP'] = $metadata[self::META_KVP_KEY_NAME];
873 $defaultType =
'array';
875 foreach (
$data as $k => &$v ) {
876 $v = is_array( $v ) ? self::applyTransformations( $v, $transforms ) : $v;
877 if ( $boolKeys !==
null && is_bool( $v ) && !isset( $boolKeys[$k] ) ) {
884 if ( is_string( $k ) ) {
885 $defaultType =
'assoc';
886 } elseif ( $k > $maxKey ) {
899 $keepMetadata = &$metadata;
902 $keepMetadata = array_intersect_key( $metadata, [
903 self::META_INDEXED_TAG_NAME => 1,
904 self::META_SUBELEMENTS => 1,
908 throw new InvalidArgumentException( __METHOD__ .
': Unknown value for "Strip"' );
912 if ( $transformTypes ===
null ) {
913 return $data + $keepMetadata;
916 if ( $defaultType ===
'array' && $maxKey !== count(
$data ) - 1 ) {
917 $defaultType =
'assoc';
921 $type = $defaultType;
922 if ( isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] !==
'default' ) {
923 $type = $metadata[self::META_TYPE];
925 if ( (
$type ===
'kvp' ||
$type ===
'BCkvp' ) &&
926 empty( $transformTypes[
'ArmorKVP'] )
929 } elseif (
$type ===
'BCarray' ) {
931 } elseif (
$type ===
'BCassoc' ) {
938 $metadata[self::META_TYPE] =
'assoc';
939 $data += $keepMetadata;
940 return empty( $transformTypes[
'AssocAsObject'] ) ?
$data : (object)
$data;
945 $metadata[self::META_TYPE] =
'array';
946 return $data + $keepMetadata;
950 $key = $metadata[self::META_KVP_KEY_NAME] ?? $transformTypes[
'ArmorKVP'];
951 $valKey = isset( $transforms[
'BC'] ) ?
'*' :
'value';
952 $assocAsObject = !empty( $transformTypes[
'AssocAsObject'] );
953 $merge = !empty( $metadata[self::META_KVP_MERGE] );
956 foreach (
$data as $k => $v ) {
957 if ( $merge && ( is_array( $v ) || is_object( $v ) ) ) {
959 if ( isset( $vArr[self::META_TYPE] ) ) {
960 $mergeType = $vArr[self::META_TYPE];
961 } elseif ( is_object( $v ) ) {
962 $mergeType =
'assoc';
964 $keys = array_keys( $vArr );
965 sort(
$keys, SORT_NUMERIC );
966 $mergeType = (
$keys === array_keys(
$keys ) ) ?
'array' :
'assoc';
971 if ( $mergeType ===
'assoc' ) {
975 if ( $strip ===
'none' ) {
976 self::setPreserveKeysList( $item, [ $key ] );
983 if ( $strip ===
'none' ) {
985 self::META_PRESERVE_KEYS => [ $key ],
986 self::META_CONTENT => $valKey,
987 self::META_TYPE =>
'assoc',
991 $ret[] = $assocAsObject ? (object)$item : $item;
993 $metadata[self::META_TYPE] =
'array';
995 return $ret + $keepMetadata;
998 throw new UnexpectedValueException(
"Unknown type '$type'" );
1013 if ( is_array(
$data ) || is_object(
$data ) ) {
1014 $isObj = is_object(
$data );
1018 $preserveKeys = isset(
$data[self::META_PRESERVE_KEYS] )
1019 ? (array)
$data[self::META_PRESERVE_KEYS]
1021 foreach (
$data as $k => $v ) {
1022 if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys,
true ) ) {
1024 } elseif ( is_array( $v ) || is_object( $v ) ) {
1025 $data[$k] = self::stripMetadata( $v );
1047 if ( !is_array( $metadata ) ) {
1050 if ( is_array(
$data ) || is_object(
$data ) ) {
1051 $isObj = is_object(
$data );
1055 $preserveKeys = isset(
$data[self::META_PRESERVE_KEYS] )
1056 ? (array)
$data[self::META_PRESERVE_KEYS]
1058 foreach (
$data as $k => $v ) {
1059 if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys,
true ) ) {
1077 private static function size( $value ) {
1079 if ( is_array( $value ) ) {
1080 foreach ( $value as $k => $v ) {
1081 if ( !self::isMetadataKey( $k ) ) {
1082 $s += self::size( $v );
1085 } elseif ( is_scalar( $value ) ) {
1086 $s = strlen( $value );
1105 $ret = &$this->data;
1106 foreach (
$path as $i => $k ) {
1107 if ( !isset( $ret[$k] ) ) {
1108 switch ( $create ) {
1113 $ret = [ $k => [] ] + $ret;
1119 $fail = implode(
'.', array_slice(
$path, 0, $i + 1 ) );
1120 throw new InvalidArgumentException(
"Path $fail does not exist" );
1123 if ( !is_array( $ret[$k] ) ) {
1124 $fail = implode(
'.', array_slice(
$path, 0, $i + 1 ) );
1125 throw new InvalidArgumentException(
"Path $fail is not an array" );
1145 foreach ( $vars as $k => $v ) {
1146 if ( is_array( $v ) || is_object( $v ) ) {
1147 $vars[$k] = self::addMetadataToResultVars( (array)$v, is_object( $v ) );
1148 } elseif ( is_bool( $v ) ) {
1152 if ( is_string( $k ) ) {
1154 } elseif ( $k > $maxKey ) {
1158 if ( !$hash && $maxKey !== count( $vars ) - 1 ) {
1166 $keys = array_diff( array_keys( $vars ), [
1167 self::META_TYPE, self::META_PRESERVE_KEYS, self::META_KVP_KEY_NAME,
1168 self::META_INDEXED_TAG_NAME, self::META_BC_BOOLS
1172 self::META_TYPE =>
'kvp',
1173 self::META_KVP_KEY_NAME =>
'key',
1174 self::META_PRESERVE_KEYS =>
$keys,
1175 self::META_BC_BOOLS => $bools,
1176 self::META_INDEXED_TAG_NAME =>
'var',
1180 self::META_TYPE =>
'array',
1181 self::META_BC_BOOLS => $bools,
1182 self::META_INDEXED_TAG_NAME =>
'value',
1197 if ( $dbInfinity ===
null ) {
1201 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)
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().
foreach( $mmfl['setupFiles'] as $fileName) if($queue) if(empty( $mmfl['quiet'])) $s