3 namespace MediaWiki\Message
;
5 use Wikimedia\Message\ITextFormatter
;
6 use Wikimedia\Message\ListParam
;
7 use Wikimedia\Message\MessageParam
;
8 use Wikimedia\Message\MessageValue
;
9 use Wikimedia\Message\ParamType
;
13 * The MediaWiki-specific implementation of ITextFormatter
15 class TextFormatter
implements ITextFormatter
{
20 * Construct a TextFormatter.
22 * The type signature may change without notice as dependencies are added
23 * to the constructor. External callers should use
24 * MediaWikiServices::getMessageFormatterFactory()
28 public function __construct( $langCode ) {
29 $this->langCode
= $langCode;
33 * Allow the Message class to be mocked in tests by constructing objects in
40 protected function createMessage( $key ) {
41 return new Message( $key );
44 public function getLangCode() {
45 return $this->langCode
;
48 private function convertParam( MessageParam
$param ) {
49 if ( $param instanceof ListParam
) {
50 $convertedElements = [];
51 foreach ( $param->getValue() as $element ) {
52 $convertedElements[] = $this->convertParam( $element );
54 return Message
::listParam( $convertedElements, $param->getListType() );
55 } elseif ( $param instanceof MessageParam
) {
56 $value = $param->getValue();
57 if ( $value instanceof MessageValue
) {
59 $value = $this->createMessage( $mv->getKey() );
60 foreach ( $mv->getParams() as $mvParam ) {
61 $value->params( $this->convertParam( $mvParam ) );
65 if ( $param->getType() === ParamType
::TEXT
) {
68 return [ $param->getType() => $value ];
71 throw new \
InvalidArgumentException( 'Invalid message parameter type' );
75 public function format( MessageValue
$mv ) {
76 $message = $this->createMessage( $mv->getKey() );
77 foreach ( $mv->getParams() as $param ) {
78 $message->params( $this->convertParam( $param ) );
80 $message->inLanguage( $this->langCode
);
81 return $message->text();