MessageTranslator.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace Elgg\I18n;
  3. /**
  4. * WARNING: API IN FLUX. DO NOT USE DIRECTLY.
  5. *
  6. * @access private
  7. *
  8. * @since 1.11
  9. */
  10. class MessageTranslator implements TranslatorInterface {
  11. // TODO Maybe this should be an array of locales to provide multiple fallbacks?
  12. /** @var Locale */
  13. private $defaultLocale;
  14. /** @var MessageBundle */
  15. private $messages;
  16. /**
  17. * Constructor
  18. *
  19. * @param Locale $defaultLocale The fallback locale
  20. * @param MessageBundle $messages Messages that this translator is aware of
  21. */
  22. public function __construct(Locale $defaultLocale, MessageBundle $messages) {
  23. $this->defaultLocale = $defaultLocale;
  24. $this->messages = $messages;
  25. }
  26. /** @inheritDoc */
  27. public function translate($key, array $args = [], Locale $locale = null) {
  28. $locales = [
  29. $locale,
  30. $this->defaultLocale,
  31. Locale::parse('en'),
  32. ];
  33. foreach ($locales as $locale) {
  34. if (!$locale) {
  35. continue;
  36. }
  37. $message = $this->messages->get($key, $locale);
  38. if ($message) {
  39. return $message->format($args);
  40. }
  41. }
  42. return $key;
  43. }
  44. }