3 namespace Drupal\locale;
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Config\ConfigFactoryInterface;
7 use Drupal\Core\Config\ConfigManagerInterface;
8 use Drupal\Core\Config\StorageInterface;
9 use Drupal\Core\Config\TypedConfigManagerInterface;
10 use Drupal\Core\StringTranslation\TranslatableMarkup;
11 use Drupal\Core\TypedData\TraversableTypedDataInterface;
12 use Drupal\Core\TypedData\TypedDataInterface;
13 use Drupal\language\ConfigurableLanguageManagerInterface;
16 * Manages configuration supported in part by interface translation.
18 * This manager is responsible to update configuration overrides and active
19 * translations when interface translation data changes. This allows Drupal to
20 * translate user roles, views, blocks, etc. after Drupal has been installed
21 * using the locale module's storage. When translations change in locale,
22 * LocaleConfigManager::updateConfigTranslations() is invoked to update the
23 * corresponding storage of the translation in the original config object or an
26 * In turn when translated configuration or configuration language overrides are
27 * changed, it is the responsibility of LocaleConfigSubscriber to update locale
30 * By design locale module only deals with sources in English.
32 * @see \Drupal\locale\LocaleConfigSubscriber
34 class LocaleConfigManager {
37 * The storage instance for reading configuration data.
39 * @var \Drupal\Core\Config\StorageInterface
41 protected $configStorage;
44 * The string storage for reading and writing translations.
46 * @var \Drupal\locale\StringStorageInterface;
48 protected $localeStorage;
51 * Array with preloaded string translations.
55 protected $translations;
58 * The configuration factory.
60 * @var \Drupal\Core\Config\ConfigFactoryInterface
62 protected $configFactory;
65 * The language manager.
67 * @var \Drupal\language\ConfigurableLanguageManagerInterface
69 protected $languageManager;
72 * The typed config manager.
74 * @var \Drupal\Core\Config\TypedConfigManagerInterface
76 protected $typedConfigManager;
79 * Whether or not configuration translations are being updated from locale.
81 * @see self::isUpdatingFromLocale()
85 protected $isUpdatingFromLocale = FALSE;
88 * The locale default config storage instance.
90 * @var \Drupal\locale\LocaleDefaultConfigStorage
92 protected $defaultConfigStorage;
95 * The configuration manager.
97 * @var \Drupal\Core\Config\ConfigManagerInterface
99 protected $configManager;
102 * Creates a new typed configuration manager.
104 * @param \Drupal\Core\Config\StorageInterface $config_storage
105 * The storage object to use for reading configuration data.
106 * @param \Drupal\locale\StringStorageInterface $locale_storage
107 * The locale storage to use for reading string translations.
108 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
109 * The configuration factory
110 * @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
111 * The typed configuration manager.
112 * @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager
113 * The language manager.
114 * @param \Drupal\locale\LocaleDefaultConfigStorage $default_config_storage
115 * The locale default configuration storage.
116 * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
117 * The configuration manager.
119 public function __construct(StorageInterface $config_storage, StringStorageInterface $locale_storage, ConfigFactoryInterface $config_factory, TypedConfigManagerInterface $typed_config, ConfigurableLanguageManagerInterface $language_manager, LocaleDefaultConfigStorage $default_config_storage, ConfigManagerInterface $config_manager) {
120 $this->configStorage = $config_storage;
121 $this->localeStorage = $locale_storage;
122 $this->configFactory = $config_factory;
123 $this->typedConfigManager = $typed_config;
124 $this->languageManager = $language_manager;
125 $this->defaultConfigStorage = $default_config_storage;
126 $this->configManager = $config_manager;
130 * Gets array of translated strings for Locale translatable configuration.
132 * @param string $name
133 * Configuration object name.
136 * Array of Locale translatable elements of the default configuration in
139 public function getTranslatableDefaultConfig($name) {
140 if ($this->isSupported($name)) {
141 // Create typed configuration wrapper based on install storage data.
142 $data = $this->defaultConfigStorage->read($name);
143 $type_definition = $this->typedConfigManager->getDefinition($name);
144 $data_definition = $this->typedConfigManager->buildDataDefinition($type_definition, $data);
145 $typed_config = $this->typedConfigManager->create($data_definition, $data);
146 if ($typed_config instanceof TraversableTypedDataInterface) {
147 return $this->getTranslatableData($typed_config);
154 * Gets translatable configuration data for a typed configuration element.
156 * @param \Drupal\Core\TypedData\TypedDataInterface $element
157 * Typed configuration element.
159 * @return array|\Drupal\Core\StringTranslation\TranslatableMarkup
160 * A nested array matching the exact structure under $element with only the
161 * elements that are translatable wrapped into a TranslatableMarkup. If the
162 * provided $element is not traversable, the return value is a single
163 * TranslatableMarkup.
165 protected function getTranslatableData(TypedDataInterface $element) {
167 if ($element instanceof TraversableTypedDataInterface) {
168 foreach ($element as $key => $property) {
169 $value = $this->getTranslatableData($property);
170 if (!empty($value)) {
171 $translatable[$key] = $value;
176 // Something is only translatable by Locale if there is a string in the
178 $value = $element->getValue();
179 $definition = $element->getDataDefinition();
180 if (!empty($definition['translatable']) && $value !== '' && $value !== NULL) {
182 if (isset($definition['translation context'])) {
183 $options['context'] = $definition['translation context'];
185 return new TranslatableMarkup($value, [], $options);
188 return $translatable;
192 * Process the translatable data array with a given language.
194 * If the given language is translatable, will return the translated copy
195 * which will only contain strings that had translations. If the given
196 * language is English and is not translatable, will return a simplified
197 * array of the English source strings only.
199 * @param string $name
200 * The configuration name.
201 * @param array $active
202 * The active configuration data.
203 * @param array|\Drupal\Core\StringTranslation\TranslatableMarkup[] $translatable
204 * The translatable array structure. A nested array matching the exact
205 * structure under of the default configuration for $name with only the
206 * elements that are translatable wrapped into a TranslatableMarkup.
207 * @param string $langcode
208 * The language code to process the array with.
211 * Processed translatable data array. Will only contain translations
212 * different from source strings or in case of untranslatable English, the
213 * source strings themselves.
215 * @see self::getTranslatableData()
217 protected function processTranslatableData($name, array $active, array $translatable, $langcode) {
219 foreach ($translatable as $key => $item) {
220 if (!isset($active[$key])) {
223 if (is_array($item)) {
224 // Only add this key if there was a translated value underneath.
225 $value = $this->processTranslatableData($name, $active[$key], $item, $langcode);
226 if (!empty($value)) {
227 $translated[$key] = $value;
231 if (locale_is_translatable($langcode)) {
232 $value = $this->translateString($name, $langcode, $item->getUntranslatedString(), $item->getOption('context'));
235 $value = $item->getUntranslatedString();
237 if (!empty($value)) {
238 $translated[$key] = $value;
246 * Saves translated configuration override.
248 * @param string $name
249 * Configuration object name.
250 * @param string $langcode
253 * Configuration data to be saved, that will be only the translated values.
255 protected function saveTranslationOverride($name, $langcode, array $data) {
256 $this->isUpdatingFromLocale = TRUE;
257 $this->languageManager->getLanguageConfigOverride($langcode, $name)->setData($data)->save();
258 $this->isUpdatingFromLocale = FALSE;
262 * Saves translated configuration data.
264 * @param string $name
265 * Configuration object name.
267 * Configuration data to be saved with translations merged in.
269 protected function saveTranslationActive($name, array $data) {
270 $this->isUpdatingFromLocale = TRUE;
271 $this->configFactory->getEditable($name)->setData($data)->save();
272 $this->isUpdatingFromLocale = FALSE;
276 * Deletes translated configuration data.
278 * @param string $name
279 * Configuration object name.
280 * @param string $langcode
283 protected function deleteTranslationOverride($name, $langcode) {
284 $this->isUpdatingFromLocale = TRUE;
285 $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
286 $this->isUpdatingFromLocale = FALSE;
290 * Gets configuration names associated with components.
292 * @param array $components
293 * (optional) Array of component lists indexed by type. If not present or it
294 * is an empty array, it will update all components.
297 * Array of configuration object names.
299 public function getComponentNames(array $components = []) {
300 $components = array_filter($components);
303 foreach ($components as $type => $list) {
304 // InstallStorage::getComponentNames returns a list of folders keyed by
306 $names = array_merge($names, $this->defaultConfigStorage->getComponentNames($type, $list));
311 return $this->defaultConfigStorage->listAll();
316 * Gets configuration names associated with strings.
319 * Array with string identifiers.
322 * Array of configuration object names.
324 public function getStringNames(array $lids) {
326 $locations = $this->localeStorage->getLocations(['sid' => $lids, 'type' => 'configuration']);
327 foreach ($locations as $location) {
328 $names[$location->name] = $location->name;
334 * Deletes configuration for language.
336 * @param string $langcode
337 * Language code to delete.
339 public function deleteLanguageTranslations($langcode) {
340 $this->isUpdatingFromLocale = TRUE;
341 $storage = $this->languageManager->getLanguageConfigOverrideStorage($langcode);
342 foreach ($storage->listAll() as $name) {
343 $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
345 $this->isUpdatingFromLocale = FALSE;
349 * Translates string using the localization system.
351 * So far we only know how to translate strings from English so the source
352 * string should be in English.
353 * Unlike regular t() translations, strings will be added to the source
354 * tables only if this is marked as default data.
356 * @param string $name
357 * Name of the configuration location.
358 * @param string $langcode
359 * Language code to translate to.
360 * @param string $source
361 * The source string, should be English.
362 * @param string $context
363 * The string context.
365 * @return string|false
366 * Translated string if there is a translation, FALSE if not.
368 public function translateString($name, $langcode, $source, $context) {
370 // If translations for a language have not been loaded yet.
371 if (!isset($this->translations[$name][$langcode])) {
372 // Preload all translations for this configuration name and language.
373 $this->translations[$name][$langcode] = [];
374 foreach ($this->localeStorage->getTranslations(['language' => $langcode, 'type' => 'configuration', 'name' => $name]) as $string) {
375 $this->translations[$name][$langcode][$string->context][$string->source] = $string;
378 if (!isset($this->translations[$name][$langcode][$context][$source])) {
379 // There is no translation of the source string in this config location
380 // to this language for this context.
381 if ($translation = $this->localeStorage->findTranslation(['source' => $source, 'context' => $context, 'language' => $langcode])) {
382 // Look for a translation of the string. It might have one, but not
383 // be saved in this configuration location yet.
384 // If the string has a translation for this context to this language,
385 // save it in the configuration location so it can be looked up faster
387 $this->localeStorage->createString((array) $translation)
388 ->addLocation('configuration', $name)
392 // No translation was found. Add the source to the configuration
393 // location so it can be translated, and the string is faster to look
395 $translation = $this->localeStorage
396 ->createString(['source' => $source, 'context' => $context])
397 ->addLocation('configuration', $name)
401 // Add an entry, either the translation found, or a blank string object
402 // to track the source string, to this configuration location, language,
404 $this->translations[$name][$langcode][$context][$source] = $translation;
407 // Return the string only when the string object had a translation.
408 if ($this->translations[$name][$langcode][$context][$source]->isTranslation()) {
409 return $this->translations[$name][$langcode][$context][$source]->getString();
416 * Reset static cache of configuration string translations.
420 public function reset() {
421 $this->translations = [];
426 * Get the translation object for the given source/context and language.
428 * @param string $name
429 * Name of the configuration location.
430 * @param string $langcode
431 * Language code to translate to.
432 * @param string $source
433 * The source string, should be English.
434 * @param string $context
435 * The string context.
437 * @return \Drupal\locale\TranslationString|false
438 * The translation object if the string was not empty or FALSE otherwise.
440 public function getStringTranslation($name, $langcode, $source, $context) {
442 $this->translateString($name, $langcode, $source, $context);
443 if ($string = $this->translations[$name][$langcode][$context][$source]) {
444 if (!$string->isTranslation()) {
445 $conditions = ['lid' => $string->lid, 'language' => $langcode];
446 $translation = $this->localeStorage->createTranslation($conditions);
447 $this->translations[$name][$langcode][$context][$source] = $translation;
459 * Checks whether a language has configuration translation.
461 * @param string $name
462 * Configuration name.
463 * @param string $langcode
467 * A boolean indicating if a language has configuration translations.
469 public function hasTranslation($name, $langcode) {
470 $translation = $this->languageManager->getLanguageConfigOverride($langcode, $name);
471 return !$translation->isNew();
475 * Returns the original language code for this shipped configuration.
477 * @param string $name
478 * The configuration name.
480 * @return null|string
481 * Language code of the default configuration for $name. If the default
482 * configuration data for $name did not contain a language code, it is
483 * assumed to be English. The return value is NULL if no such default
484 * configuration exists.
486 public function getDefaultConfigLangcode($name) {
487 // Config entities that do not have the 'default_config_hash' cannot be
488 // shipped configuration regardless of whether there is a name match.
489 // configurable_language entities are a special case since they can be
490 // translated regardless of whether they are shipped if they in the standard
492 $config_entity_type = $this->configManager->getEntityTypeIdByName($name);
493 if (!$config_entity_type || $config_entity_type === 'configurable_language'
494 || !empty($this->configFactory->get($name)->get('_core.default_config_hash'))
496 $shipped = $this->defaultConfigStorage->read($name);
497 if (!empty($shipped)) {
498 return !empty($shipped['langcode']) ? $shipped['langcode'] : 'en';
505 * Returns the current language code for this active configuration.
507 * @param string $name
508 * The configuration name.
510 * @return null|string
511 * Language code of the current active configuration for $name. If the
512 * configuration data for $name did not contain a language code, it is
513 * assumed to be English. The return value is NULL if no such active
514 * configuration exists.
516 public function getActiveConfigLangcode($name) {
517 $active = $this->configStorage->read($name);
518 if (!empty($active)) {
519 return !empty($active['langcode']) ? $active['langcode'] : 'en';
524 * Whether the given configuration is supported for interface translation.
526 * @param string $name
527 * The configuration name.
530 * TRUE if interface translation is supported.
532 public function isSupported($name) {
533 return $this->getDefaultConfigLangcode($name) == 'en' && $this->configStorage->read($name);
537 * Indicates whether configuration translations are being updated from locale.
540 * Whether or not configuration translations are currently being updated.
541 * If TRUE, LocaleConfigManager is in control of the process and the
542 * reference data is locale's storage. Changes made to active configuration
543 * and overrides in this case should not feed back to locale storage.
544 * On the other hand, when not updating from locale and configuration
545 * translations change, we need to feed back to the locale storage.
547 public function isUpdatingTranslationsFromLocale() {
548 return $this->isUpdatingFromLocale;
552 * Updates all configuration translations for the names / languages provided.
554 * To be used when interface translation changes result in the need to update
555 * configuration translations to keep them in sync.
557 * @param array $names
558 * Array of names of configuration objects to update.
559 * @param array $langcodes
560 * (optional) Array of language codes to update. Defaults to all
561 * configurable languages.
564 * Total number of configuration override and active configuration objects
565 * updated (saved or removed).
567 public function updateConfigTranslations(array $names, array $langcodes = []) {
568 $langcodes = $langcodes ? $langcodes : array_keys($this->languageManager->getLanguages());
570 foreach ($names as $name) {
571 $translatable = $this->getTranslatableDefaultConfig($name);
572 if (empty($translatable)) {
573 // If there is nothing translatable in this configuration or not
574 // supported, skip it.
578 $active_langcode = $this->getActiveConfigLangcode($name);
579 $active = $this->configStorage->read($name);
581 foreach ($langcodes as $langcode) {
582 $processed = $this->processTranslatableData($name, $active, $translatable, $langcode);
583 // If the language code is not the same as the active storage
584 // language, we should update the configuration override.
585 if ($langcode != $active_langcode) {
586 $override = $this->languageManager->getLanguageConfigOverride($langcode, $name);
587 // Filter out locale managed configuration keys so that translations
588 // removed from Locale will be reflected in the config override.
589 $data = $this->filterOverride($override->get(), $translatable);
590 if (!empty($processed)) {
591 // Merge in the Locale managed translations with existing data.
592 $data = NestedArray::mergeDeepArray([$data, $processed], TRUE);
594 if (empty($data) && !$override->isNew()) {
595 // The configuration override contains Locale overrides that no
597 $this->deleteTranslationOverride($name, $langcode);
600 elseif (!empty($data)) {
601 // Update translation data in configuration override.
602 $this->saveTranslationOverride($name, $langcode, $data);
606 elseif (locale_is_translatable($langcode)) {
607 // If the language code is the active storage language, we should
608 // update. If it is English, we should only update if English is also
610 $active = NestedArray::mergeDeepArray([$active, $processed], TRUE);
611 $this->saveTranslationActive($name, $active);
620 * Filters override data based on default translatable items.
622 * @param array $override_data
623 * Configuration override data.
624 * @param array $translatable
625 * Translatable data array. @see self::getTranslatableData()
627 * Nested array of any items of $override_data which did not have keys in
628 * $translatable. May be empty if $override_data only had items which were
629 * also in $translatable.
631 protected function filterOverride(array $override_data, array $translatable) {
633 foreach ($override_data as $key => $value) {
634 if (isset($translatable[$key])) {
635 // If the translatable default configuration has this key, look further
636 // for subkeys or ignore this element for scalar values.
637 if (is_array($value)) {
638 $value = $this->filterOverride($value, $translatable[$key]);
639 if (!empty($value)) {
640 $filtered_data[$key] = $value;
645 // If this key was not in the translatable default configuration,
647 $filtered_data[$key] = $value;
650 return $filtered_data;