Debian Codegraph @

includes/api/ApiResult.php

raw symbols SCIP
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Api;
22
23 use Exception;
24 use InvalidArgumentException;
25 use MediaWiki\MediaWikiServices;
26 use MediaWiki\Message\Message;
27 use RuntimeException;
28 use stdClass;
29 use UnexpectedValueException;
30 use Wikimedia\Message\ListParam;
31 use Wikimedia\Message\ScalarParam;
32
33 /**
34 * This class represents the result of the API operations.
35 * It simply wraps a nested array structure, adding some functions to simplify
36 * array's modifications. As various modules execute, they add different pieces
37 * of information to this result, structuring it as it will be given to the client.
38 *
39 * Each subarray may either be a dictionary - key-value pairs with unique keys,
40 * or lists, where the items are added using $data[] = $value notation.
41 *
42 * @since 1.25 this is no longer a subclass of ApiBase
43 * @ingroup API
44 */
45 class ApiResult implements ApiSerializable {
46
47 /**
48 * Override existing value in addValue(), setValue(), and similar functions
49 * @since 1.21
50 */
51 public const OVERRIDE = 1;
52
53 /**
54 * For addValue(), setValue() and similar functions, if the value does not
55 * exist, add it as the first element. In case the new value has no name
56 * (numerical index), all indexes will be renumbered.
57 * @since 1.21
58 */
59 public const ADD_ON_TOP = 2;
60
61 /**
62 * For addValue() and similar functions, do not check size while adding a value
63 * Don't use this unless you REALLY know what you're doing.
64 * Values added while the size checking was disabled will never be counted.
65 * Ignored for setValue() and similar functions.
66 * @since 1.24
67 */
68 public const NO_SIZE_CHECK = 4;
69
70 /**
71 * For addValue(), setValue() and similar functions, do not validate data.
72 * Also disables size checking. If you think you need to use this, you're
73 * probably wrong.
74 * @since 1.25
75 */
76 public const NO_VALIDATE = self::NO_SIZE_CHECK | 8;
77
78 /**
79 * For addValue(), setValue() and similar functions, do allow override
80 * of conflicting keys.
81 * @since 1.45 (also backported to 1.43.6, 1.44.3)
82 */
83 public const IGNORE_CONFLICT_KEYS = 16;
84
85 /**
86 * Key for the 'indexed tag name' metadata item. Value is string.
87 * @since 1.25
88 */
89 public const META_INDEXED_TAG_NAME = '_element';
90
91 /**
92 * Key for the 'subelements' metadata item. Value is string[].
93 * @since 1.25
94 */
95 public const META_SUBELEMENTS = '_subelements';
96
97 /**
98 * Key for the 'preserve keys' metadata item. Value is string[].
99 * @since 1.25
100 */
101 public const META_PRESERVE_KEYS = '_preservekeys';
102
103 /**
104 * Key for the 'content' metadata item. Value is string.
105 * @since 1.25
106 */
107 public const META_CONTENT = '_content';
108
109 /**
110 * Key for the 'type' metadata item. Value is one of the following strings:
111 * - default: Like 'array' if all (non-metadata) keys are numeric with no
112 * gaps, otherwise like 'assoc'.
113 * - array: Keys are used for ordering, but are not output. In a format
114 * like JSON, outputs as [].
115 * - assoc: In a format like JSON, outputs as {}.
116 * - kvp: For a format like XML where object keys have a restricted
117 * character set, use an alternative output format. For example,
118 * <container><item name="key">value</item></container> rather than
119 * <container key="value" />
120 * - BCarray: Like 'array' normally, 'default' in backwards-compatibility mode.
121 * - BCassoc: Like 'assoc' normally, 'default' in backwards-compatibility mode.
122 * - BCkvp: Like 'kvp' normally. In backwards-compatibility mode, forces
123 * the alternative output format for all formats, for example
124 * [{"name":key,"*":value}] in JSON. META_KVP_KEY_NAME must also be set.
125 * @since 1.25
126 */
127 public const META_TYPE = '_type';
128
129 /**
130 * Key for the metadata item whose value specifies the name used for the
131 * kvp key in the alternative output format with META_TYPE 'kvp' or
132 * 'BCkvp', i.e. the "name" in <container><item name="key">value</item></container>.
133 * Value is string.
134 * @since 1.25
135 */
136 public const META_KVP_KEY_NAME = '_kvpkeyname';
137
138 /**
139 * Key for the metadata item that indicates that the KVP key should be
140 * added into an assoc value, i.e. {"key":{"val1":"a","val2":"b"}}
141 * transforms to {"name":"key","val1":"a","val2":"b"} rather than
142 * {"name":"key","value":{"val1":"a","val2":"b"}}.
143 * Value is boolean.
144 * @since 1.26
145 */
146 public const META_KVP_MERGE = '_kvpmerge';
147
148 /**
149 * Key for the 'BC bools' metadata item. Value is string[].
150 * Note no setter is provided.
151 * @since 1.25
152 */
153 public const META_BC_BOOLS = '_BC_bools';
154
155 /**
156 * Key for the 'BC subelements' metadata item. Value is string[].
157 * Note no setter is provided.
158 * @since 1.25
159 */
160 public const META_BC_SUBELEMENTS = '_BC_subelements';
161
162 /** @var mixed */
163 private $data;
164 private int $size;
165 /** @var int|false */
166 private $maxSize;
167 private ApiErrorFormatter $errorFormatter;
168
169 /**
170 * @param int|false $maxSize Maximum result "size", or false for no limit
171 */
172 public function __construct( $maxSize ) {
173 $this->maxSize = $maxSize;
174 $this->reset();
175 }
176
177 /**
178 * @since 1.25
179 * @param ApiErrorFormatter $formatter
180 */
181 public function setErrorFormatter( ApiErrorFormatter $formatter ) {
182 $this->errorFormatter = $formatter;
183 }
184
185 /**
186 * Allow for adding one ApiResult into another
187 * @since 1.25
188 * @return mixed
189 */
190 public function serializeForApiResult() {
191 return $this->data;
192 }
193
194 /***************************************************************************/
195 // region Content
196 /** @name Content */
197
198 /**
199 * Clear the current result data.
200 */
201 public function reset() {
202 $this->data = [
203 self::META_TYPE => 'assoc', // Usually what's desired
204 ];
205 $this->size = 0;
206 }
207
208 /**
209 * Get the result data array
210 *
211 * The returned value should be considered read-only.
212 *
213 * Transformations include:
214 *
215 * Custom: (callable) Applied before other transformations. Signature is
216 * function ( &$data, &$metadata ), return value is ignored. Called for
217 * each nested array.
218 *
219 * BC: (array) This transformation does various adjustments to bring the
220 * output in line with the pre-1.25 result format. The value array is a
221 * list of flags: 'nobool', 'no*', 'nosub'.
222 * - Boolean-valued items are changed to '' if true or removed if false,
223 * unless listed in META_BC_BOOLS. This may be skipped by including
224 * 'nobool' in the value array.
225 * - The tag named by META_CONTENT is renamed to '*', and META_CONTENT is
226 * set to '*'. This may be skipped by including 'no*' in the value
227 * array.
228 * - Tags listed in META_BC_SUBELEMENTS will have their values changed to
229 * [ '*' => $value ]. This may be skipped by including 'nosub' in
230 * the value array.
231 * - If META_TYPE is 'BCarray', set it to 'default'
232 * - If META_TYPE is 'BCassoc', set it to 'default'
233 * - If META_TYPE is 'BCkvp', perform the transformation (even if
234 * the Types transformation is not being applied).
235 *
236 * Types: (assoc) Apply transformations based on META_TYPE. The values
237 * array is an associative array with the following possible keys:
238 * - AssocAsObject: (bool) If true, return arrays with META_TYPE 'assoc'
239 * as objects.
240 * - ArmorKVP: (string) If provided, transform arrays with META_TYPE 'kvp'
241 * and 'BCkvp' into arrays of two-element arrays, something like this:
242 * $output = [];
243 * foreach ( $input as $key => $value ) {
244 * $pair = [];
245 * $pair[$META_KVP_KEY_NAME ?: $ArmorKVP_value] = $key;
246 * ApiResult::setContentValue( $pair, 'value', $value );
247 * $output[] = $pair;
248 * }
249 *
250 * Strip: (string) Strips metadata keys from the result.
251 * - 'all': Strip all metadata, recursively
252 * - 'base': Strip metadata at the top-level only.
253 * - 'none': Do not strip metadata.
254 * - 'bc': Like 'all', but leave certain pre-1.25 keys.
255 *
256 * @since 1.25
257 * @param array|string|null $path Path to fetch, see ApiResult::addValue
258 * @param array $transforms See above
259 * @return mixed Result data, or null if not found
260 */
261 public function getResultData( $path = [], $transforms = [] ) {
262 $path = (array)$path;
263 if ( !$path ) {
264 return self::applyTransformations( $this->data, $transforms );
265 }
266
267 $last = array_pop( $path );
268 $ret = &$this->path( $path, 'dummy' );
269 if ( !isset( $ret[$last] ) ) {
270 return null;
271 } elseif ( is_array( $ret[$last] ) ) {
272 return self::applyTransformations( $ret[$last], $transforms );
273 } else {
274 return $ret[$last];
275 }
276 }
277
278 /**
279 * Get the size of the result, i.e. the amount of bytes in it
280 * @return int
281 */
282 public function getSize() {
283 return $this->size;
284 }
285
286 /**
287 * Add an output value to the array by name.
288 *
289 * Verifies that value with the same name has not been added before.
290 *
291 * @since 1.25
292 * @param array &$arr To add $value to
293 * @param string|int|null $name Index of $arr to add $value at,
294 * or null to use the next numeric index.
295 * @param mixed $value
296 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
297 */
298 public static function setValue( array &$arr, $name, $value, $flags = 0 ) {
299 if ( ( $flags & self::NO_VALIDATE ) !== self::NO_VALIDATE ) {
300 $value = self::validateValue( $value );
301 }
302
303 if ( $name === null ) {
304 if ( $flags & self::ADD_ON_TOP ) {
305 array_unshift( $arr, $value );
306 } else {
307 $arr[] = $value;
308 }
309 return;
310 }
311
312 $exists = isset( $arr[$name] );
313 if ( !$exists || ( $flags & self::OVERRIDE ) ) {
314 if ( !$exists && ( $flags & self::ADD_ON_TOP ) ) {
315 $arr = [ $name => $value ] + $arr;
316 } else {
317 $arr[$name] = $value;
318 }
319 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
320 $conflicts = array_intersect_key( $arr[$name], $value );
321 if ( !$conflicts || ( $flags & self::IGNORE_CONFLICT_KEYS ) ) {
322 $arr[$name] += $value;
323 } else {
324 $keys = implode( ', ', array_keys( $conflicts ) );
325 throw new RuntimeException(
326 "Conflicting keys ($keys) when attempting to merge element $name"
327 );
328 }
329 } elseif ( $value !== $arr[$name] ) {
330 throw new RuntimeException(
331 "Attempting to add element $name=$value, existing value is {$arr[$name]}"
332 );
333 }
334 }
335
336 /**
337 * Validate a value for addition to the result
338 * @param mixed $value
339 * @return array|mixed|string
340 */
341 private static function validateValue( $value ) {
342 if ( is_object( $value ) ) {
343 // Note we use is_callable() here instead of instanceof because
344 // ApiSerializable is an informal protocol (see docs there for details).
345 if ( is_callable( [ $value, 'serializeForApiResult' ] ) ) {
346 $oldValue = $value;
347 $value = $value->serializeForApiResult();
348 if ( is_object( $value ) ) {
349 throw new UnexpectedValueException(
350 get_class( $oldValue ) . '::serializeForApiResult() returned an object of class ' .
351 get_class( $value )
352 );
353 }
354
355 // Recursive call instead of fall-through so we can throw a
356 // better exception message.
357 try {
358 return self::validateValue( $value );
359 } catch ( Exception $ex ) {
360 throw new UnexpectedValueException(
361 get_class( $oldValue ) . '::serializeForApiResult() returned an invalid value: ' .
362 $ex->getMessage(),
363 0,
364 $ex
365 );
366 }
367 } elseif ( $value instanceof ScalarParam || $value instanceof ListParam ) {
368 // HACK Support code that puts $msg->getParams() directly into API responses
369 // (e.g. ApiErrorFormatter::formatRawMessage()).
370 $value = $value->getType() === 'text' ? $value->getValue() : $value->toJsonArray();
371 } elseif ( is_callable( [ $value, '__toString' ] ) ) {
372 $value = (string)$value;
373 } else {
374 $value = (array)$value + [ self::META_TYPE => 'assoc' ];
375 }
376 }
377
378 if ( is_string( $value ) ) {
379 // Optimization: avoid querying the service locator for each value.
380 static $contentLanguage = null;
381 if ( !$contentLanguage ) {
382 $contentLanguage = MediaWikiServices::getInstance()->getContentLanguage();
383 }
384 $value = $contentLanguage->normalize( $value );
385 } elseif ( is_array( $value ) ) {
386 foreach ( $value as $k => $v ) {
387 $value[$k] = self::validateValue( $v );
388 }
389 } elseif ( $value !== null && !is_scalar( $value ) ) {
390 $type = get_debug_type( $value );
391 throw new InvalidArgumentException( "Cannot add $type to ApiResult" );
392 } elseif ( is_float( $value ) && !is_finite( $value ) ) {
393 throw new InvalidArgumentException( 'Cannot add non-finite floats to ApiResult' );
394 }
395
396 return $value;
397 }
398
399 /**
400 * Add value to the output data at the given path.
401 *
402 * Path can be an indexed array, each element specifying the branch at which to add the new
403 * value. Setting $path to [ 'a', 'b', 'c' ] is equivalent to data['a']['b']['c'] = $value.
404 * If $path is null, the value will be inserted at the data root.
405 *
406 * @param array|string|int|null $path
407 * @param string|int|null $name See ApiResult::setValue()
408 * @param mixed $value
409 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
410 * This parameter used to be boolean, and the value of OVERRIDE=1 was specifically
411 * chosen so that it would be backwards compatible with the new method signature.
412 * @return bool True if $value fits in the result, false if not
413 * @since 1.21 int $flags replaced boolean $override
414 */
415 public function addValue( $path, $name, $value, $flags = 0 ) {
416 $arr = &$this->path( $path, ( $flags & self::ADD_ON_TOP ) ? 'prepend' : 'append' );
417
418 if ( !( $flags & self::NO_SIZE_CHECK ) ) {
419 // self::size needs the validated value. Then flag
420 // to not re-validate later.
421 $value = self::validateValue( $value );
422 $flags |= self::NO_VALIDATE;
423
424 $newsize = $this->size + self::size( $value );
425 if ( $this->maxSize !== false && $newsize > $this->maxSize ) {
426 $this->errorFormatter->addWarning(
427 'result', [ 'apiwarn-truncatedresult', Message::numParam( $this->maxSize ) ]
428 );
429 return false;
430 }
431 $this->size = $newsize;
432 }
433
434 self::setValue( $arr, $name, $value, $flags );
435 return true;
436 }
437
438 /**
439 * Remove an output value to the array by name.
440 * @param array &$arr To remove $value from
441 * @param string|int $name Index of $arr to remove
442 * @return mixed Old value, or null
443 */
444 public static function unsetValue( array &$arr, $name ) {
445 $ret = null;
446 if ( isset( $arr[$name] ) ) {
447 $ret = $arr[$name];
448 unset( $arr[$name] );
449 }
450 return $ret;
451 }
452
453 /**
454 * Remove value from the output data at the given path.
455 *
456 * @since 1.25
457 * @param array|string|null $path See ApiResult::addValue()
458 * @param string|int|null $name Index to remove at $path.
459 * If null, $path itself is removed.
460 * @param int $flags Flags used when adding the value
461 * @return mixed Old value, or null
462 */
463 public function removeValue( $path, $name, $flags = 0 ) {
464 $path = (array)$path;
465 if ( $name === null ) {
466 if ( !$path ) {
467 throw new InvalidArgumentException( 'Cannot remove the data root' );
468 }
469 $name = array_pop( $path );
470 }
471 $ret = self::unsetValue( $this->path( $path, 'dummy' ), $name );
472 if ( !( $flags & self::NO_SIZE_CHECK ) ) {
473 $newsize = $this->size - self::size( $ret );
474 $this->size = max( $newsize, 0 );
475 }
476 return $ret;
477 }
478
479 /**
480 * Add an output value to the array by name and mark as META_CONTENT.
481 *
482 * @since 1.25
483 * @param array &$arr To add $value to
484 * @param string|int $name Index of $arr to add $value at.
485 * @param mixed $value
486 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
487 */
488 public static function setContentValue( array &$arr, $name, $value, $flags = 0 ) {
489 if ( $name === null ) {
490 throw new InvalidArgumentException( 'Content value must be named' );
491 }
492 self::setContentField( $arr, $name, $flags );
493 self::setValue( $arr, $name, $value, $flags );
494 }
495
496 /**
497 * Add value to the output data at the given path and mark as META_CONTENT
498 *
499 * @since 1.25
500 * @param array|string|null $path See ApiResult::addValue()
501 * @param string|int $name See ApiResult::setValue()
502 * @param mixed $value
503 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
504 * @return bool True if $value fits in the result, false if not
505 */
506 public function addContentValue( $path, $name, $value, $flags = 0 ) {
507 if ( $name === null ) {
508 throw new InvalidArgumentException( 'Content value must be named' );
509 }
510 $this->addContentField( $path, $name, $flags );
511 return $this->addValue( $path, $name, $value, $flags );
512 }
513
514 /**
515 * Add the numeric limit for a limit=max to the result.
516 *
517 * @since 1.25
518 * @param string $moduleName
519 * @param int $limit
520 */
521 public function addParsedLimit( $moduleName, $limit ) {
522 // Add value, allowing overwriting
523 $this->addValue( 'limits', $moduleName, $limit,
524 self::OVERRIDE | self::NO_SIZE_CHECK );
525 }
526
527 // endregion -- end of Content
528
529 /***************************************************************************/
530 // region Metadata
531 /** @name Metadata */
532
533 /**
534 * Set the name of the content field name (META_CONTENT)
535 *
536 * @since 1.25
537 * @param array &$arr
538 * @param string|int $name Name of the field
539 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
540 */
541 public static function setContentField( array &$arr, $name, $flags = 0 ) {
542 if ( isset( $arr[self::META_CONTENT] ) &&
543 isset( $arr[$arr[self::META_CONTENT]] ) &&
544 !( $flags & self::OVERRIDE )
545 ) {
546 throw new RuntimeException(
547 "Attempting to set content element as $name when " . $arr[self::META_CONTENT] .
548 ' is already set as the content element'
549 );
550 }
551 $arr[self::META_CONTENT] = $name;
552 }
553
554 /**
555 * Set the name of the content field name (META_CONTENT)
556 *
557 * @since 1.25
558 * @param array|string|null $path See ApiResult::addValue()
559 * @param string|int $name Name of the field
560 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
561 */
562 public function addContentField( $path, $name, $flags = 0 ) {
563 $arr = &$this->path( $path, ( $flags & self::ADD_ON_TOP ) ? 'prepend' : 'append' );
564 self::setContentField( $arr, $name, $flags );
565 }
566
567 /**
568 * Causes the elements with the specified names to be output as
569 * subelements rather than attributes.
570 * @since 1.25 is static
571 * @param array &$arr
572 * @param array|string|int $names The element name(s) to be output as subelements
573 */
574 public static function setSubelementsList( array &$arr, $names ) {
575 if ( !isset( $arr[self::META_SUBELEMENTS] ) ) {
576 $arr[self::META_SUBELEMENTS] = (array)$names;
577 } else {
578 $arr[self::META_SUBELEMENTS] = array_merge( $arr[self::META_SUBELEMENTS], (array)$names );
579 }
580 }
581
582 /**
583 * Causes the elements with the specified names to be output as
584 * subelements rather than attributes.
585 * @since 1.25
586 * @param array|string|null $path See ApiResult::addValue()
587 * @param array|string|int $names The element name(s) to be output as subelements
588 */
589 public function addSubelementsList( $path, $names ) {
590 $arr = &$this->path( $path );
591 self::setSubelementsList( $arr, $names );
592 }
593
594 /**
595 * Causes the elements with the specified names to be output as
596 * attributes (when possible) rather than as subelements.
597 * @since 1.25
598 * @param array &$arr
599 * @param array|string|int $names The element name(s) to not be output as subelements
600 */
601 public static function unsetSubelementsList( array &$arr, $names ) {
602 if ( isset( $arr[self::META_SUBELEMENTS] ) ) {
603 $arr[self::META_SUBELEMENTS] = array_diff( $arr[self::META_SUBELEMENTS], (array)$names );
604 }
605 }
606
607 /**
608 * Causes the elements with the specified names to be output as
609 * attributes (when possible) rather than as subelements.
610 * @since 1.25
611 * @param array|string|null $path See ApiResult::addValue()
612 * @param array|string|int $names The element name(s) to not be output as subelements
613 */
614 public function removeSubelementsList( $path, $names ) {
615 $arr = &$this->path( $path );
616 self::unsetSubelementsList( $arr, $names );
617 }
618
619 /**
620 * Set the tag name for numeric-keyed values in XML format
621 * @since 1.25 is static
622 * @param array &$arr
623 * @param string $tag Tag name
624 */
625 public static function setIndexedTagName( array &$arr, $tag ) {
626 if ( !is_string( $tag ) ) {
627 throw new InvalidArgumentException( 'Bad tag name' );
628 }
629 $arr[self::META_INDEXED_TAG_NAME] = $tag;
630 }
631
632 /**
633 * Set the tag name for numeric-keyed values in XML format
634 * @since 1.25
635 * @param array|string|null $path See ApiResult::addValue()
636 * @param string $tag Tag name
637 */
638 public function addIndexedTagName( $path, $tag ) {
639 $arr = &$this->path( $path );
640 self::setIndexedTagName( $arr, $tag );
641 }
642
643 /**
644 * Set indexed tag name on $arr and all subarrays
645 *
646 * @since 1.25
647 * @param array &$arr
648 * @param string $tag Tag name
649 */
650 public static function setIndexedTagNameRecursive( array &$arr, $tag ) {
651 if ( !is_string( $tag ) ) {
652 throw new InvalidArgumentException( 'Bad tag name' );
653 }
654 $arr[self::META_INDEXED_TAG_NAME] = $tag;
655 foreach ( $arr as $k => &$v ) {
656 if ( is_array( $v ) && !self::isMetadataKey( $k ) ) {
657 self::setIndexedTagNameRecursive( $v, $tag );
658 }
659 }
660 }
661
662 /**
663 * Set indexed tag name on $path and all subarrays
664 *
665 * @since 1.25
666 * @param array|string|null $path See ApiResult::addValue()
667 * @param string $tag Tag name
668 */
669 public function addIndexedTagNameRecursive( $path, $tag ) {
670 $arr = &$this->path( $path );
671 self::setIndexedTagNameRecursive( $arr, $tag );
672 }
673
674 /**
675 * Preserve specified keys.
676 *
677 * This prevents XML name mangling and preventing keys from being removed
678 * by self::stripMetadata().
679 *
680 * @since 1.25
681 * @param array &$arr
682 * @param array|string $names The element name(s) to preserve
683 */
684 public static function setPreserveKeysList( array &$arr, $names ) {
685 if ( !isset( $arr[self::META_PRESERVE_KEYS] ) ) {
686 $arr[self::META_PRESERVE_KEYS] = (array)$names;
687 } else {
688 $arr[self::META_PRESERVE_KEYS] = array_merge( $arr[self::META_PRESERVE_KEYS], (array)$names );
689 }
690 }
691
692 /**
693 * Preserve specified keys.
694 * @since 1.25
695 * @see self::setPreserveKeysList()
696 * @param array|string|null $path See ApiResult::addValue()
697 * @param array|string $names The element name(s) to preserve
698 */
699 public function addPreserveKeysList( $path, $names ) {
700 $arr = &$this->path( $path );
701 self::setPreserveKeysList( $arr, $names );
702 }
703
704 /**
705 * Don't preserve specified keys.
706 * @since 1.25
707 * @see self::setPreserveKeysList()
708 * @param array &$arr
709 * @param array|string $names The element name(s) to not preserve
710 */
711 public static function unsetPreserveKeysList( array &$arr, $names ) {
712 if ( isset( $arr[self::META_PRESERVE_KEYS] ) ) {
713 $arr[self::META_PRESERVE_KEYS] = array_diff( $arr[self::META_PRESERVE_KEYS], (array)$names );
714 }
715 }
716
717 /**
718 * Don't preserve specified keys.
719 * @since 1.25
720 * @see self::setPreserveKeysList()
721 * @param array|string|null $path See ApiResult::addValue()
722 * @param array|string $names The element name(s) to not preserve
723 */
724 public function removePreserveKeysList( $path, $names ) {
725 $arr = &$this->path( $path );
726 self::unsetPreserveKeysList( $arr, $names );
727 }
728
729 /**
730 * Set the array data type
731 *
732 * @since 1.25
733 * @param array &$arr
734 * @param string $type See ApiResult::META_TYPE
735 * @param string|null $kvpKeyName See ApiResult::META_KVP_KEY_NAME
736 */
737 public static function setArrayType( array &$arr, $type, $kvpKeyName = null ) {
738 if ( !in_array( $type, [
739 'default', 'array', 'assoc', 'kvp', 'BCarray', 'BCassoc', 'BCkvp'
740 ], true ) ) {
741 throw new InvalidArgumentException( 'Bad type' );
742 }
743 $arr[self::META_TYPE] = $type;
744 if ( is_string( $kvpKeyName ) ) {
745 $arr[self::META_KVP_KEY_NAME] = $kvpKeyName;
746 }
747 }
748
749 /**
750 * Set the array data type for a path
751 * @since 1.25
752 * @param array|string|null $path See ApiResult::addValue()
753 * @param string $tag See ApiResult::META_TYPE
754 * @param string|null $kvpKeyName See ApiResult::META_KVP_KEY_NAME
755 */
756 public function addArrayType( $path, $tag, $kvpKeyName = null ) {
757 $arr = &$this->path( $path );
758 self::setArrayType( $arr, $tag, $kvpKeyName );
759 }
760
761 /**
762 * Set the array data type recursively
763 * @since 1.25
764 * @param array &$arr
765 * @param string $type See ApiResult::META_TYPE
766 * @param string|null $kvpKeyName See ApiResult::META_KVP_KEY_NAME
767 */
768 public static function setArrayTypeRecursive( array &$arr, $type, $kvpKeyName = null ) {
769 self::setArrayType( $arr, $type, $kvpKeyName );
770 foreach ( $arr as $k => &$v ) {
771 if ( is_array( $v ) && !self::isMetadataKey( $k ) ) {
772 self::setArrayTypeRecursive( $v, $type, $kvpKeyName );
773 }
774 }
775 }
776
777 /**
778 * Set the array data type for a path recursively
779 * @since 1.25
780 * @param array|string|null $path See ApiResult::addValue()
781 * @param string $tag See ApiResult::META_TYPE
782 * @param string|null $kvpKeyName See ApiResult::META_KVP_KEY_NAME
783 */
784 public function addArrayTypeRecursive( $path, $tag, $kvpKeyName = null ) {
785 $arr = &$this->path( $path );
786 self::setArrayTypeRecursive( $arr, $tag, $kvpKeyName );
787 }
788
789 // endregion -- end of Metadata
790
791 /***************************************************************************/
792 // region Utility
793 /** @name Utility */
794
795 /**
796 * Test whether a key should be considered metadata
797 *
798 * @param string|int $key
799 * @return bool
800 */
801 public static function isMetadataKey( $key ) {
802 return str_starts_with( $key, '_' );
803 }
804
805 /**
806 * Apply transformations to an array, returning the transformed array.
807 *
808 * @see ApiResult::getResultData()
809 * @since 1.25
810 * @param array $dataIn
811 * @param array $transforms
812 * @return array|stdClass
813 */
814 protected static function applyTransformations( array $dataIn, array $transforms ) {
815 $strip = $transforms['Strip'] ?? 'none';
816 if ( $strip === 'base' ) {
817 $transforms['Strip'] = 'none';
818 }
819 $transformTypes = $transforms['Types'] ?? null;
820 if ( $transformTypes !== null && !is_array( $transformTypes ) ) {
821 throw new InvalidArgumentException( __METHOD__ . ':Value for "Types" must be an array' );
822 }
823
824 $metadata = [];
825 $data = self::stripMetadataNonRecursive( $dataIn, $metadata );
826
827 if ( isset( $transforms['Custom'] ) ) {
828 if ( !is_callable( $transforms['Custom'] ) ) {
829 throw new InvalidArgumentException( __METHOD__ . ': Value for "Custom" must be callable' );
830 }
831 call_user_func_array( $transforms['Custom'], [ &$data, &$metadata ] );
832 }
833
834 if ( ( isset( $transforms['BC'] ) || $transformTypes !== null ) &&
835 isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] === 'BCkvp' &&
836 !isset( $metadata[self::META_KVP_KEY_NAME] )
837 ) {
838 throw new UnexpectedValueException( 'Type "BCkvp" used without setting ' .
839 'ApiResult::META_KVP_KEY_NAME metadata item' );
840 }
841
842 // BC transformations
843 $boolKeys = null;
844 if ( isset( $transforms['BC'] ) ) {
845 if ( !is_array( $transforms['BC'] ) ) {
846 throw new InvalidArgumentException( __METHOD__ . ':Value for "BC" must be an array' );
847 }
848 if ( !in_array( 'nobool', $transforms['BC'], true ) ) {
849 $boolKeys = isset( $metadata[self::META_BC_BOOLS] )
850 ? array_fill_keys( $metadata[self::META_BC_BOOLS], true )
851 : [];
852 }
853
854 if ( !in_array( 'no*', $transforms['BC'], true ) &&
855 isset( $metadata[self::META_CONTENT] ) && $metadata[self::META_CONTENT] !== '*'
856 ) {
857 $k = $metadata[self::META_CONTENT];
858 $data['*'] = $data[$k];
859 unset( $data[$k] );
860 $metadata[self::META_CONTENT] = '*';
861 }
862
863 if ( !in_array( 'nosub', $transforms['BC'], true ) &&
864 isset( $metadata[self::META_BC_SUBELEMENTS] )
865 ) {
866 foreach ( $metadata[self::META_BC_SUBELEMENTS] as $k ) {
867 if ( isset( $data[$k] ) ) {
868 $data[$k] = [
869 '*' => $data[$k],
870 self::META_CONTENT => '*',
871 self::META_TYPE => 'assoc',
872 ];
873 }
874 }
875 }
876
877 if ( isset( $metadata[self::META_TYPE] ) ) {
878 switch ( $metadata[self::META_TYPE] ) {
879 case 'BCarray':
880 case 'BCassoc':
881 $metadata[self::META_TYPE] = 'default';
882 break;
883 case 'BCkvp':
884 $transformTypes['ArmorKVP'] = $metadata[self::META_KVP_KEY_NAME];
885 break;
886 }
887 }
888 }
889
890 // Figure out type, do recursive calls, and do boolean transform if necessary
891 $defaultType = 'array';
892 $maxKey = -1;
893 foreach ( $data as $k => &$v ) {
894 $v = is_array( $v ) ? self::applyTransformations( $v, $transforms ) : $v;
895 if ( $boolKeys !== null && is_bool( $v ) && !isset( $boolKeys[$k] ) ) {
896 if ( !$v ) {
897 unset( $data[$k] );
898 continue;
899 }
900 $v = '';
901 }
902 if ( is_string( $k ) ) {
903 $defaultType = 'assoc';
904 } elseif ( $k > $maxKey ) {
905 $maxKey = $k;
906 }
907 }
908 unset( $v );
909
910 // Determine which metadata to keep
911 switch ( $strip ) {
912 case 'all':
913 case 'base':
914 $keepMetadata = [];
915 break;
916 case 'none':
917 $keepMetadata = &$metadata;
918 break;
919 case 'bc':
920 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal Type mismatch on pass-by-ref args
921 $keepMetadata = array_intersect_key( $metadata, [
922 self::META_INDEXED_TAG_NAME => 1,
923 self::META_SUBELEMENTS => 1,
924 ] );
925 break;
926 default:
927 throw new InvalidArgumentException( __METHOD__ . ': Unknown value for "Strip"' );
928 }
929
930 // No type transformation
931 if ( $transformTypes === null ) {
932 return $data + $keepMetadata;
933 }
934
935 if ( $defaultType === 'array' && $maxKey !== count( $data ) - 1 ) {
936 $defaultType = 'assoc';
937 }
938
939 // Override type, if provided
940 $type = $defaultType;
941 if ( isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] !== 'default' ) {
942 $type = $metadata[self::META_TYPE];
943 }
944 if ( ( $type === 'kvp' || $type === 'BCkvp' ) &&
945 empty( $transformTypes['ArmorKVP'] )
946 ) {
947 $type = 'assoc';
948 } elseif ( $type === 'BCarray' ) {
949 $type = 'array';
950 } elseif ( $type === 'BCassoc' ) {
951 $type = 'assoc';
952 }
953
954 // Apply transformation
955 switch ( $type ) {
956 case 'assoc':
957 $metadata[self::META_TYPE] = 'assoc';
958 $data += $keepMetadata;
959 return empty( $transformTypes['AssocAsObject'] ) ? $data : (object)$data;
960
961 case 'array':
962 // Sort items in ascending order by key. Note that $data may contain a mix of number and string keys,
963 // for which the sorting behavior of krsort() with SORT_REGULAR is inconsistent between PHP versions.
964 // Given a comparison of a string key and a number key, PHP < 8.2 coerces the string key into a number
965 // (which yields zero if the string was non-numeric), and then performs the comparison,
966 // while PHP >= 8.2 makes the behavior consistent with stricter numeric comparisons introduced by
967 // PHP 8.0 in that if the string key is non-numeric, it converts the number key into a string
968 // and compares those two strings instead. We therefore use a custom comparison function
969 // implementing PHP >= 8.2 ordering semantics to ensure consistent ordering of items
970 // irrespective of the PHP version (T326480).
971 uksort( $data, static function ( $a, $b ): int {
972 // In a comparison of a number or numeric string with a non-numeric string,
973 // coerce both values into a string prior to comparing and compare the resulting strings.
974 if ( is_numeric( $a ) xor is_numeric( $b ) ) {
975 return (string)$a <=> (string)$b;
976 }
977
978 return $a <=> $b;
979 } );
980
981 $data = array_values( $data );
982 $metadata[self::META_TYPE] = 'array';
983 // @phan-suppress-next-line PhanTypeMismatchReturnNullable Type mismatch on pass-by-ref args
984 return $data + $keepMetadata;
985
986 case 'kvp':
987 case 'BCkvp':
988 $key = $metadata[self::META_KVP_KEY_NAME] ?? $transformTypes['ArmorKVP'];
989 $valKey = isset( $transforms['BC'] ) ? '*' : 'value';
990 $assocAsObject = !empty( $transformTypes['AssocAsObject'] );
991 $merge = !empty( $metadata[self::META_KVP_MERGE] );
992
993 $ret = [];
994 foreach ( $data as $k => $v ) {
995 if ( $merge && ( is_array( $v ) || is_object( $v ) ) ) {
996 $vArr = (array)$v;
997 if ( isset( $vArr[self::META_TYPE] ) ) {
998 $mergeType = $vArr[self::META_TYPE];
999 } elseif ( is_object( $v ) ) {
1000 $mergeType = 'assoc';
1001 } else {
1002 $keys = array_keys( $vArr );
1003 sort( $keys, SORT_NUMERIC );
1004 $mergeType = ( $keys === array_keys( $keys ) ) ? 'array' : 'assoc';
1005 }
1006 } else {
1007 $mergeType = 'n/a';
1008 }
1009 if ( $mergeType === 'assoc' ) {
1010 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable vArr set when used
1011 $item = $vArr + [
1012 $key => $k,
1013 ];
1014 if ( $strip === 'none' ) {
1015 self::setPreserveKeysList( $item, [ $key ] );
1016 }
1017 } else {
1018 $item = [
1019 $key => $k,
1020 $valKey => $v,
1021 ];
1022 if ( $strip === 'none' ) {
1023 $item += [
1024 self::META_PRESERVE_KEYS => [ $key ],
1025 self::META_CONTENT => $valKey,
1026 self::META_TYPE => 'assoc',
1027 ];
1028 }
1029 }
1030 $ret[] = $assocAsObject ? (object)$item : $item;
1031 }
1032 $metadata[self::META_TYPE] = 'array';
1033
1034 // @phan-suppress-next-line PhanTypeMismatchReturnNullable Type mismatch on pass-by-ref args
1035 return $ret + $keepMetadata;
1036
1037 default:
1038 throw new UnexpectedValueException( "Unknown type '$type'" );
1039 }
1040 }
1041
1042 /**
1043 * Recursively remove metadata keys from a data array or object
1044 *
1045 * Note this removes all potential metadata keys, not just the defined
1046 * ones.
1047 *
1048 * @since 1.25
1049 * @param array|stdClass $data
1050 * @return array|stdClass
1051 */
1052 public static function stripMetadata( $data ) {
1053 if ( is_array( $data ) || is_object( $data ) ) {
1054 $isObj = is_object( $data );
1055 if ( $isObj ) {
1056 $data = (array)$data;
1057 }
1058 $preserveKeys = isset( $data[self::META_PRESERVE_KEYS] )
1059 ? (array)$data[self::META_PRESERVE_KEYS]
1060 : [];
1061 foreach ( $data as $k => $v ) {
1062 if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
1063 unset( $data[$k] );
1064 } elseif ( is_array( $v ) || is_object( $v ) ) {
1065 $data[$k] = self::stripMetadata( $v );
1066 }
1067 }
1068 if ( $isObj ) {
1069 $data = (object)$data;
1070 }
1071 }
1072 return $data;
1073 }
1074
1075 /**
1076 * Remove metadata keys from a data array or object, non-recursive
1077 *
1078 * Note this removes all potential metadata keys, not just the defined
1079 * ones.
1080 *
1081 * @since 1.25
1082 * @param array|stdClass $data
1083 * @param array|null &$metadata Store metadata here, if provided
1084 * @return array|stdClass
1085 */
1086 public static function stripMetadataNonRecursive( $data, &$metadata = null ) {
1087 if ( !is_array( $metadata ) ) {
1088 $metadata = [];
1089 }
1090 if ( is_array( $data ) || is_object( $data ) ) {
1091 $isObj = is_object( $data );
1092 if ( $isObj ) {
1093 $data = (array)$data;
1094 }
1095 $preserveKeys = isset( $data[self::META_PRESERVE_KEYS] )
1096 ? (array)$data[self::META_PRESERVE_KEYS]
1097 : [];
1098 foreach ( $data as $k => $v ) {
1099 if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
1100 $metadata[$k] = $v;
1101 unset( $data[$k] );
1102 }
1103 }
1104 if ( $isObj ) {
1105 $data = (object)$data;
1106 }
1107 }
1108 return $data;
1109 }
1110
1111 /**
1112 * Get the 'real' size of a result item. This means the strlen() of the item,
1113 * or the sum of the strlen()s of the elements if the item is an array.
1114 * @param mixed $value Validated value (see self::validateValue())
1115 * @return int
1116 */
1117 private static function size( $value ) {
1118 $s = 0;
1119 if ( is_array( $value ) ) {
1120 foreach ( $value as $k => $v ) {
1121 if ( !self::isMetadataKey( $k ) ) {
1122 $s += self::size( $v );
1123 }
1124 }
1125 } elseif ( is_scalar( $value ) ) {
1126 $s = strlen( $value );
1127 }
1128
1129 return $s;
1130 }
1131
1132 /**
1133 * Return a reference to the internal data at $path
1134 *
1135 * @param array|string|null $path
1136 * @param string $create
1137 * If 'append', append empty arrays.
1138 * If 'prepend', prepend empty arrays.
1139 * If 'dummy', return a dummy array.
1140 * Else, raise an error.
1141 * @return array
1142 */
1143 private function &path( $path, $create = 'append' ) {
1144 $path = (array)$path;
1145 $ret = &$this->data;
1146 foreach ( $path as $i => $k ) {
1147 if ( !isset( $ret[$k] ) ) {
1148 switch ( $create ) {
1149 case 'append':
1150 $ret[$k] = [];
1151 break;
1152 case 'prepend':
1153 $ret = [ $k => [] ] + $ret;
1154 break;
1155 case 'dummy':
1156 $tmp = [];
1157 return $tmp;
1158 default:
1159 $fail = implode( '.', array_slice( $path, 0, $i + 1 ) );
1160 throw new InvalidArgumentException( "Path $fail does not exist" );
1161 }
1162 }
1163 if ( !is_array( $ret[$k] ) ) {
1164 $fail = implode( '.', array_slice( $path, 0, $i + 1 ) );
1165 throw new InvalidArgumentException( "Path $fail is not an array" );
1166 }
1167 $ret = &$ret[$k];
1168 }
1169 return $ret;
1170 }
1171
1172 /**
1173 * Add the correct metadata to an array of vars we want to export through
1174 * the API.
1175 *
1176 * @param array $vars
1177 * @param bool $forceHash
1178 * @return array
1179 */
1180 public static function addMetadataToResultVars( $vars, $forceHash = true ) {
1181 // Process subarrays and determine if this is a JS [] or {}
1182 $hash = $forceHash;
1183 $maxKey = -1;
1184 $bools = [];
1185 foreach ( $vars as $k => $v ) {
1186 if ( is_array( $v ) || is_object( $v ) ) {
1187 $vars[$k] = self::addMetadataToResultVars( (array)$v, is_object( $v ) );
1188 } elseif ( is_bool( $v ) ) {
1189 // Better here to use real bools even in BC formats
1190 $bools[] = $k;
1191 }
1192 if ( is_string( $k ) ) {
1193 $hash = true;
1194 } elseif ( $k > $maxKey ) {
1195 $maxKey = $k;
1196 }
1197 }
1198 if ( !$hash && $maxKey !== count( $vars ) - 1 ) {
1199 $hash = true;
1200 }
1201
1202 // Set metadata appropriately
1203 if ( $hash ) {
1204 // Get the list of keys we actually care about. Unfortunately, we can't support
1205 // certain keys that conflict with ApiResult metadata.
1206 $keys = array_diff( array_keys( $vars ), [
1207 self::META_TYPE, self::META_PRESERVE_KEYS, self::META_KVP_KEY_NAME,
1208 self::META_INDEXED_TAG_NAME, self::META_BC_BOOLS
1209 ] );
1210
1211 return [
1212 self::META_TYPE => 'kvp',
1213 self::META_KVP_KEY_NAME => 'key',
1214 self::META_PRESERVE_KEYS => $keys,
1215 self::META_BC_BOOLS => $bools,
1216 self::META_INDEXED_TAG_NAME => 'var',
1217 ] + $vars;
1218 } else {
1219 return [
1220 self::META_TYPE => 'array',
1221 self::META_BC_BOOLS => $bools,
1222 self::META_INDEXED_TAG_NAME => 'value',
1223 ] + $vars;
1224 }
1225 }
1226
1227 /**
1228 * Format an expiry timestamp for API output
1229 * @since 1.29
1230 * @param string $expiry Expiry timestamp, likely from the database
1231 * @param string $infinity Use this string for infinite expiry
1232 * (only use this to maintain backward compatibility with existing output)
1233 * @return string Formatted expiry
1234 */
1235 public static function formatExpiry( $expiry, $infinity = 'infinity' ) {
1236 static $dbInfinity;
1237 $dbInfinity ??= MediaWikiServices::getInstance()->getConnectionProvider()
1238 ->getReplicaDatabase()
1239 ->getInfinity();
1240
1241 if ( $expiry === '' || $expiry === null || $expiry === false ||
1242 wfIsInfinity( $expiry ) || $expiry === $dbInfinity
1243 ) {
1244 return $infinity;
1245 } else {
1246 return wfTimestamp( TS_ISO_8601, $expiry );
1247 }
1248 }
1249
1250 // endregion -- end of Utility
1251
1252 }
1253
1254 /*
1255 * This file uses VisualStudio style region/endregion fold markers which are
1256 * recognised by PHPStorm. If modelines are enabled, the following editor
1257 * configuration will also enable folding in vim, if it is in the last 5 lines
1258 * of the file. We also use "@name" which creates sections in Doxygen.
1259 *
1260 * vim: foldmarker=//\ region,//\ endregion foldmethod=marker
1261 */
1262
1263 /** @deprecated class alias since 1.43 */
1264 class_alias( ApiResult::class, 'ApiResult' );