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 static function convertParam( MessageParam
$param ) {
49 if ( $param instanceof ListParam
) {
50 $convertedElements = [];
51 foreach ( $param->getValue() as $element ) {
52 $convertedElements[] = self
::convertParam( $element );
54 return Message
::listParam( $convertedElements, $param->getListType() );
55 } elseif ( $param instanceof MessageParam
) {
56 if ( $param->getType() === ParamType
::TEXT
) {
57 return $param->getValue();
59 return [ $param->getType() => $param->getValue() ];
62 throw new \
InvalidArgumentException( 'Invalid message parameter type' );
66 public function format( MessageValue
$mv ) {
67 $message = $this->createMessage( $mv->getKey() );
68 foreach ( $mv->getParams() as $param ) {
69 $message->params( self
::convertParam( $param ) );
71 $message->inLanguage( $this->langCode
);
72 return $message->text();