| 1 |
<?php |
| 2 |
|
| 3 |
namespace Wikimedia\Message; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
use Stringable; |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
class ScalarParam extends MessageParam { |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
public function __construct( $type, $value ) { |
| 31 |
if ( !in_array( $type, ParamType::cases() ) ) { |
| 32 |
throw new InvalidArgumentException( '$type must be one of the ParamType constants' ); |
| 33 |
} |
| 34 |
if ( $type === ParamType::LIST ) { |
| 35 |
throw new InvalidArgumentException( |
| 36 |
'ParamType::LIST cannot be used with ScalarParam; use ListParam instead' |
| 37 |
); |
| 38 |
} |
| 39 |
if ( $type === ParamType::OBJECT ) { |
| 40 |
wfDeprecatedMsg( 'Using ParamType::OBJECT was deprecated in MediaWiki 1.43', '1.43' ); |
| 41 |
} elseif ( $value instanceof MessageSpecifier ) { |
| 42 |
|
| 43 |
|
| 44 |
$value = MessageValue::newFromSpecifier( $value ); |
| 45 |
} elseif ( is_object( $value ) && $value instanceof Stringable ) { |
| 46 |
$value = (string)$value; |
| 47 |
} elseif ( !is_string( $value ) && !is_numeric( $value ) ) { |
| 48 |
$valType = get_debug_type( $value ); |
| 49 |
if ( $value === null || is_bool( $value ) ) { |
| 50 |
wfDeprecatedMsg( "Using $valType as message parameter was deprecated in MediaWiki 1.43", '1.43' ); |
| 51 |
$value = (string)$value; |
| 52 |
} else { |
| 53 |
throw new InvalidArgumentException( |
| 54 |
"Scalar parameter must be a string, number, Stringable, or MessageSpecifier; got $valType" |
| 55 |
); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
$this->type = $type; |
| 60 |
$this->value = $value; |
| 61 |
} |
| 62 |
|
| 63 |
public function dump() { |
| 64 |
if ( $this->value instanceof MessageValue ) { |
| 65 |
$contents = $this->value->dump(); |
| 66 |
} else { |
| 67 |
$contents = htmlspecialchars( (string)$this->value ); |
| 68 |
} |
| 69 |
return "<{$this->type}>" . $contents . "</{$this->type}>"; |
| 70 |
} |
| 71 |
|
| 72 |
public function toJsonArray(): array { |
| 73 |
|
| 74 |
|
| 75 |
return [ |
| 76 |
$this->type => $this->value, |
| 77 |
]; |
| 78 |
} |
| 79 |
|
| 80 |
|
| 81 |
public static function jsonClassHintFor( string $keyName ) { |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
return MessageValue::hint(); |
| 86 |
} |
| 87 |
|
| 88 |
public static function newFromJsonArray( array $json ): ScalarParam { |
| 89 |
|
| 90 |
|
| 91 |
if ( count( $json ) !== 1 ) { |
| 92 |
throw new InvalidArgumentException( 'Invalid format' ); |
| 93 |
} |
| 94 |
|
| 95 |
foreach ( $json as $type => $value ) { |
| 96 |
return new self( $type, $value ); |
| 97 |
} |
| 98 |
} |
| 99 |
} |