Debian Codegraph @

includes/libs/Message/ListParam.php

raw symbols SCIP
1 <?php
2
3 namespace Wikimedia\Message;
4
5 use InvalidArgumentException;
6 use Wikimedia\JsonCodec\Hint;
7
8 /**
9 * Value object representing a message parameter that consists of a list of values.
10 *
11 * Message parameter classes are pure value objects and are newable and (de)serializable.
12 *
13 * @newable
14 */
15 class ListParam extends MessageParam {
16
17 /** @var string */
18 private $listType;
19
20 /**
21 * @stable to call.
22 *
23 * @param string $listType One of the ListType constants.
24 * @param (MessageParam|MessageSpecifier|string|int|float)[] $elements Values in the list.
25 * Values that are not instances of MessageParam are wrapped using ParamType::TEXT.
26 */
27 public function __construct( $listType, array $elements ) {
28 if ( !in_array( $listType, ListType::cases() ) ) {
29 throw new InvalidArgumentException( '$listType must be one of the ListType constants' );
30 }
31 $this->type = ParamType::LIST;
32 $this->listType = $listType;
33 $this->value = [];
34 foreach ( $elements as $element ) {
35 if ( $element instanceof MessageParam ) {
36 $this->value[] = $element;
37 } else {
38 $this->value[] = new ScalarParam( ParamType::TEXT, $element );
39 }
40 }
41 }
42
43 /**
44 * Get the type of the list
45 *
46 * @return string One of the ListType constants
47 */
48 public function getListType() {
49 return $this->listType;
50 }
51
52 public function dump() {
53 $contents = '';
54 foreach ( $this->value as $element ) {
55 $contents .= $element->dump();
56 }
57 return "<{$this->type} listType=\"{$this->listType}\">$contents</{$this->type}>";
58 }
59
60 public function toJsonArray(): array {
61 // WARNING: When changing how this class is serialized, follow the instructions
62 // at <https://www.mediawiki.org/wiki/Manual:Parser_cache/Serialization_compatibility>!
63 return [
64 $this->type => $this->value,
65 'type' => $this->listType,
66 ];
67 }
68
69 /** @inheritDoc */
70 public static function jsonClassHintFor( string $keyName ) {
71 // Reduce serialization overhead by eliminating the type information
72 // when the list consists of MessageParam instances
73 if ( $keyName === ParamType::LIST ) {
74 return Hint::build(
75 MessageParam::class, Hint::INHERITED,
76 Hint::LIST, Hint::USE_SQUARE,
77 Hint::ONLY_FOR_DECODE
78 );
79 }
80 return null;
81 }
82
83 public static function newFromJsonArray( array $json ): ListParam {
84 // WARNING: When changing how this class is serialized, follow the instructions
85 // at <https://www.mediawiki.org/wiki/Manual:Parser_cache/Serialization_compatibility>!
86 if ( count( $json ) !== 2 || !isset( $json[ParamType::LIST] ) || !isset( $json['type'] ) ) {
87 throw new InvalidArgumentException( 'Invalid format' );
88 }
89 return new self( $json['type'], $json[ParamType::LIST] );
90 }
91 }