3 namespace Wikimedia\Message
;
6 * Value object representing a message for i18n with alternative
7 * machine-readable data.
9 * This augments a MessageValue with an additional machine-readable code and
10 * structured data. The intended use is to facilitate error reporting in APIs.
12 * For example, a MessageValue reporting an "integer out of range" error might
13 * use one of three message keys, depending on whether there is a minimum, a
14 * maximum, or both. But an API would likely want to use one code for all three
15 * cases, and would likely want the endpoints represented along the lines of
16 * `[ 'min' => 1, 'max' => 10 ]` rather than
17 * `[ 0 => new ScalarParam( ParamType::TEXT, 1 ), 1 => new ScalarParam( ParamType::TEXT, 10 ) ]`.
19 * DataMessageValues are pure value objects and are safely newable.
23 class DataMessageValue
extends MessageValue
{
27 /** @var array|null */
34 * @param (MessageParam|MessageValue|string|int|float)[] $params
35 * @param string|null $code String representing the concept behind
37 * @param array|null $data Structured data representing the concept
38 * behind this message.
40 public function __construct( $key, $params = [], $code = null, array $data = null ) {
41 parent
::__construct( $key, $params );
43 $this->code
= $code ??
$key;
48 * Static constructor for easier chaining of `->params()` methods
50 * @param (MessageParam|MessageValue|string|int|float)[] $params
51 * @param string|null $code
52 * @param array|null $data
53 * @return DataMessageValue
55 public static function new( $key, $params = [], $code = null, array $data = null ) {
56 return new DataMessageValue( $key, $params, $code, $data );
60 * Get the message code
63 public function getCode() {
68 * Get the message's structured data
71 public function getData() {
75 public function dump() {
77 if ( $this->getParams() ) {
78 $contents = '<params>';
79 foreach ( $this->getParams() as $param ) {
80 $contents .= $param->dump();
82 $contents .= '</params>';
85 if ( $this->data
!== null ) {
86 $contents .= '<data>' . htmlspecialchars( json_encode( $this->data
), ENT_NOQUOTES
) . '</data>';
89 return '<datamessage key="' . htmlspecialchars( $this->getKey() ) . '"'
90 . ' code="' . htmlspecialchars( $this->code
) . '">'