Merge "Add .pipeline/ with dev image variant"
[lhc/web/wiklou.git] / includes / Message / TextFormatter.php
1 <?php
2
3 namespace MediaWiki\Message;
4
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;
10 use Message;
11
12 /**
13 * The MediaWiki-specific implementation of ITextFormatter
14 */
15 class TextFormatter implements ITextFormatter {
16 /** @var string */
17 private $langCode;
18
19 /**
20 * Construct a TextFormatter.
21 *
22 * The type signature may change without notice as dependencies are added
23 * to the constructor. External callers should use
24 * MediaWikiServices::getMessageFormatterFactory()
25 *
26 * @internal
27 */
28 public function __construct( $langCode ) {
29 $this->langCode = $langCode;
30 }
31
32 /**
33 * Allow the Message class to be mocked in tests by constructing objects in
34 * a protected method.
35 *
36 * @internal
37 * @param string $key
38 * @return Message
39 */
40 protected function createMessage( $key ) {
41 return new Message( $key );
42 }
43
44 public function getLangCode() {
45 return $this->langCode;
46 }
47
48 private function convertParam( MessageParam $param ) {
49 if ( $param instanceof ListParam ) {
50 $convertedElements = [];
51 foreach ( $param->getValue() as $element ) {
52 $convertedElements[] = $this->convertParam( $element );
53 }
54 return Message::listParam( $convertedElements, $param->getListType() );
55 } elseif ( $param instanceof MessageParam ) {
56 $value = $param->getValue();
57 if ( $value instanceof MessageValue ) {
58 $mv = $value;
59 $value = $this->createMessage( $mv->getKey() );
60 foreach ( $mv->getParams() as $mvParam ) {
61 $value->params( $this->convertParam( $mvParam ) );
62 }
63 }
64
65 if ( $param->getType() === ParamType::TEXT ) {
66 return $value;
67 } else {
68 return [ $param->getType() => $value ];
69 }
70 } else {
71 throw new \InvalidArgumentException( 'Invalid message parameter type' );
72 }
73 }
74
75 public function format( MessageValue $mv ) {
76 $message = $this->createMessage( $mv->getKey() );
77 foreach ( $mv->getParams() as $param ) {
78 $message->params( $this->convertParam( $param ) );
79 }
80 $message->inLanguage( $this->langCode );
81 return $message->text();
82 }
83 }