3 namespace Drupal\Core\StringTranslation\Translator;
6 * String translator with a static cache for translations.
8 * This is a high performance way to provide a handful of string replacements.
10 class StaticTranslation implements TranslatorInterface {
16 * Array of cached translations indexed by language and context.
18 protected $translations;
21 * Constructs a translator from an array of translations.
23 * @param array $translations
24 * Array of override strings indexed by language and context
26 public function __construct($translations = []) {
27 $this->translations = $translations;
33 public function getStringTranslation($langcode, $string, $context) {
34 if (!isset($this->translations[$langcode])) {
35 $this->translations[$langcode] = $this->getLanguage($langcode);
37 if (isset($this->translations[$langcode][$context][$string])) {
38 return $this->translations[$langcode][$context][$string];
48 public function reset() {
49 $this->translations = [];
53 * Retrieves translations for a given language.
55 * @param string $langcode
56 * The langcode of the language.
59 * A multidimensional array of translations, indexed by the context the
60 * source string belongs to. The second level is using original strings as
61 * keys. An empty array will be returned when no translations are available.
63 protected function getLanguage($langcode) {
64 // This class is usually a base class but we do not declare as abstract
65 // because it can be used on its own, by passing a simple array on the
66 // constructor. This can be useful while testing, but it does not support
67 // loading specific languages. All available languages should be passed
68 // in the constructor array.