StaticTranslation.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Drupal\Core\StringTranslation\Translator;
  3. /**
  4. * String translator with a static cache for translations.
  5. *
  6. * This is a high performance way to provide a handful of string replacements.
  7. */
  8. class StaticTranslation implements TranslatorInterface {
  9. /**
  10. * String translations
  11. *
  12. * @var array
  13. * Array of cached translations indexed by language and context.
  14. */
  15. protected $translations;
  16. /**
  17. * Constructs a translator from an array of translations.
  18. *
  19. * @param array $translations
  20. * Array of override strings indexed by language and context
  21. */
  22. public function __construct($translations = []) {
  23. $this->translations = $translations;
  24. }
  25. /**
  26. * {@inheritdoc}
  27. */
  28. public function getStringTranslation($langcode, $string, $context) {
  29. if (!isset($this->translations[$langcode])) {
  30. $this->translations[$langcode] = $this->getLanguage($langcode);
  31. }
  32. if (isset($this->translations[$langcode][$context][$string])) {
  33. return $this->translations[$langcode][$context][$string];
  34. }
  35. else {
  36. return FALSE;
  37. }
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function reset() {
  43. $this->translations = [];
  44. }
  45. /**
  46. * Retrieves translations for a given language.
  47. *
  48. * @param string $langcode
  49. * The langcode of the language.
  50. *
  51. * @return array
  52. * A multidimensional array of translations, indexed by the context the
  53. * source string belongs to. The second level is using original strings as
  54. * keys. An empty array will be returned when no translations are available.
  55. */
  56. protected function getLanguage($langcode) {
  57. // This class is usually a base class but we do not declare as abstract
  58. // because it can be used on its own, by passing a simple array on the
  59. // constructor. This can be useful while testing, but it does not support
  60. // loading specific languages. All available languages should be passed
  61. // in the constructor array.
  62. return [];
  63. }
  64. }