wiki.techinc.nl/includes/libs/Message/ListParam.php
Bartosz Dziewoński c7f52f0ddb Make MessageValue implement JsonDeserializable
MessageValue and friends are pure value objects and newable, so
it makes sense for them to be (de)serializable too. There are some
places where we want to serialize messages, such as in ParserOutput.

The structure of the resulting JSON is inspired by the way we
represent Message objects as plain values elsewhere in MediaWiki,
e.g. StatusValue::getStatusArray().

Co-Authored-By: C. Scott Ananian <cscott@cscott.net>
Depends-On: Ia32f95a6bdf342262b4ef044140527f0676402b9
Depends-On: I7bafe80cd36c2558517f474871148286350a4e76
Change-Id: Id47d58b5e26707fa0e0dbdd37418c0d54c8dd503
2024-06-12 15:47:37 -04:00

72 lines
2.1 KiB
PHP

<?php
namespace Wikimedia\Message;
use InvalidArgumentException;
use MediaWiki\Json\JsonDeserializer;
/**
* Value object representing a message parameter that consists of a list of values.
*
* Message parameter classes are pure value objects and are newable and (de)serializable.
*
* @newable
*/
class ListParam extends MessageParam {
private $listType;
/**
* @stable to call.
*
* @param string $listType One of the ListType constants.
* @param (MessageParam|MessageValue|string|int|float)[] $elements Values in the list.
* Values that are not instances of MessageParam are wrapped using ParamType::TEXT.
*/
public function __construct( $listType, array $elements ) {
$this->type = ParamType::LIST;
$this->listType = $listType;
$this->value = [];
foreach ( $elements as $element ) {
if ( $element instanceof MessageParam ) {
$this->value[] = $element;
} else {
$this->value[] = new ScalarParam( ParamType::TEXT, $element );
}
}
}
/**
* Get the type of the list
*
* @return string One of the ListType constants
*/
public function getListType() {
return $this->listType;
}
public function dump() {
$contents = '';
foreach ( $this->value as $element ) {
$contents .= $element->dump();
}
return "<{$this->type} listType=\"{$this->listType}\">$contents</{$this->type}>";
}
public function toJsonArray(): array {
// WARNING: When changing how this class is serialized, follow the instructions
// at <https://www.mediawiki.org/wiki/Manual:Parser_cache/Serialization_compatibility>!
return [
$this->type => $this->value,
'type' => $this->listType,
];
}
public static function newFromJsonArray( JsonDeserializer $deserializer, array $json ) {
// WARNING: When changing how this class is serialized, follow the instructions
// at <https://www.mediawiki.org/wiki/Manual:Parser_cache/Serialization_compatibility>!
if ( count( $json ) !== 2 || !isset( $json[ParamType::LIST] ) || !isset( $json['type'] ) ) {
throw new InvalidArgumentException( 'Invalid format' );
}
return new self( $json['type'], $json[ParamType::LIST] );
}
}