| 1 |
<?php |
| 2 |
|
| 3 |
namespace Wikimedia\Message; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
use Wikimedia\JsonCodec\Hint; |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
class ListParam extends MessageParam { |
| 16 |
|
| 17 |
|
| 18 |
private $listType; |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 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 |
|
| 45 |
|
| 46 |
|
| 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 |
|
| 62 |
|
| 63 |
return [ |
| 64 |
$this->type => $this->value, |
| 65 |
'type' => $this->listType, |
| 66 |
]; |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
public static function jsonClassHintFor( string $keyName ) { |
| 71 |
|
| 72 |
|
| 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 |
|
| 85 |
|
| 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 |
} |