TextFormatter.php 2.1 KB

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