Provide command to adjust phpunit.xml for code coverage
[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 static function convertParam( MessageParam $param ) {
49 if ( $param instanceof ListParam ) {
50 $convertedElements = [];
51 foreach ( $param->getValue() as $element ) {
52 $convertedElements[] = self::convertParam( $element );
53 }
54 return Message::listParam( $convertedElements, $param->getListType() );
55 } elseif ( $param instanceof MessageParam ) {
56 if ( $param->getType() === ParamType::TEXT ) {
57 return $param->getValue();
58 } else {
59 return [ $param->getType() => $param->getValue() ];
60 }
61 } else {
62 throw new \InvalidArgumentException( 'Invalid message parameter type' );
63 }
64 }
65
66 public function format( MessageValue $mv ) {
67 $message = $this->createMessage( $mv->getKey() );
68 foreach ( $mv->getParams() as $param ) {
69 $message->params( self::convertParam( $param ) );
70 }
71 $message->inLanguage( $this->langCode );
72 return $message->text();
73 }
74 }