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 $typed_config = $this->typedConfigManager->createFromNameAndData($name, $data);
144 if ($typed_config instanceof TraversableTypedDataInterface) {
145 return $this->getTranslatableData($typed_config);
152 * Gets translatable configuration data for a typed configuration element.
154 * @param \Drupal\Core\TypedData\TypedDataInterface $element
155 * Typed configuration element.
157 * @return array|\Drupal\Core\StringTranslation\TranslatableMarkup
158 * A nested array matching the exact structure under $element with only the
159 * elements that are translatable wrapped into a TranslatableMarkup. If the
160 * provided $element is not traversable, the return value is a single
161 * TranslatableMarkup.
163 protected function getTranslatableData(TypedDataInterface $element) {
165 if ($element instanceof TraversableTypedDataInterface) {
166 foreach ($element as $key => $property) {
167 $value = $this->getTranslatableData($property);
168 if (!empty($value)) {
169 $translatable[$key] = $value;
174 // Something is only translatable by Locale if there is a string in the
176 $value = $element->getValue();
177 $definition = $element->getDataDefinition();
178 if (!empty($definition['translatable']) && $value !== '' && $value !== NULL) {
180 if (isset($definition['translation context'])) {
181 $options['context'] = $definition['translation context'];
183 return new TranslatableMarkup($value, [], $options);
186 return $translatable;
190 * Process the translatable data array with a given language.
192 * If the given language is translatable, will return the translated copy
193 * which will only contain strings that had translations. If the given
194 * language is English and is not translatable, will return a simplified
195 * array of the English source strings only.
197 * @param string $name
198 * The configuration name.
199 * @param array $active
200 * The active configuration data.
201 * @param array|\Drupal\Core\StringTranslation\TranslatableMarkup[] $translatable
202 * The translatable array structure. A nested array matching the exact
203 * structure under of the default configuration for $name with only the
204 * elements that are translatable wrapped into a TranslatableMarkup.
205 * @param string $langcode
206 * The language code to process the array with.
209 * Processed translatable data array. Will only contain translations
210 * different from source strings or in case of untranslatable English, the
211 * source strings themselves.
213 * @see self::getTranslatableData()
215 protected function processTranslatableData($name, array $active, array $translatable, $langcode) {
217 foreach ($translatable as $key => $item) {
218 if (!isset($active[$key])) {
221 if (is_array($item)) {
222 // Only add this key if there was a translated value underneath.
223 $value = $this->processTranslatableData($name, $active[$key], $item, $langcode);
224 if (!empty($value)) {
225 $translated[$key] = $value;
229 if (locale_is_translatable($langcode)) {
230 $value = $this->translateString($name, $langcode, $item->getUntranslatedString(), $item->getOption('context'));
233 $value = $item->getUntranslatedString();
235 if (!empty($value)) {
236 $translated[$key] = $value;
244 * Saves translated configuration override.
246 * @param string $name
247 * Configuration object name.
248 * @param string $langcode
251 * Configuration data to be saved, that will be only the translated values.
253 protected function saveTranslationOverride($name, $langcode, array $data) {
254 $this->isUpdatingFromLocale = TRUE;
255 $this->languageManager->getLanguageConfigOverride($langcode, $name)->setData($data)->save();
256 $this->isUpdatingFromLocale = FALSE;
260 * Saves translated configuration data.
262 * @param string $name
263 * Configuration object name.
265 * Configuration data to be saved with translations merged in.
267 protected function saveTranslationActive($name, array $data) {
268 $this->isUpdatingFromLocale = TRUE;
269 $this->configFactory->getEditable($name)->setData($data)->save();
270 $this->isUpdatingFromLocale = FALSE;
274 * Deletes translated configuration data.
276 * @param string $name
277 * Configuration object name.
278 * @param string $langcode
281 protected function deleteTranslationOverride($name, $langcode) {
282 $this->isUpdatingFromLocale = TRUE;
283 $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
284 $this->isUpdatingFromLocale = FALSE;
288 * Gets configuration names associated with components.
290 * @param array $components
291 * (optional) Array of component lists indexed by type. If not present or it
292 * is an empty array, it will update all components.
295 * Array of configuration object names.
297 public function getComponentNames(array $components = []) {
298 $components = array_filter($components);
301 foreach ($components as $type => $list) {
302 // InstallStorage::getComponentNames returns a list of folders keyed by
304 $names = array_merge($names, $this->defaultConfigStorage->getComponentNames($type, $list));
309 return $this->defaultConfigStorage->listAll();
314 * Gets configuration names associated with strings.
317 * Array with string identifiers.
320 * Array of configuration object names.
322 public function getStringNames(array $lids) {
324 $locations = $this->localeStorage->getLocations(['sid' => $lids, 'type' => 'configuration']);
325 foreach ($locations as $location) {
326 $names[$location->name] = $location->name;
332 * Deletes configuration for language.
334 * @param string $langcode
335 * Language code to delete.
337 public function deleteLanguageTranslations($langcode) {
338 $this->isUpdatingFromLocale = TRUE;
339 $storage = $this->languageManager->getLanguageConfigOverrideStorage($langcode);
340 foreach ($storage->listAll() as $name) {
341 $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
343 $this->isUpdatingFromLocale = FALSE;
347 * Translates string using the localization system.
349 * So far we only know how to translate strings from English so the source
350 * string should be in English.
351 * Unlike regular t() translations, strings will be added to the source
352 * tables only if this is marked as default data.
354 * @param string $name
355 * Name of the configuration location.
356 * @param string $langcode
357 * Language code to translate to.
358 * @param string $source
359 * The source string, should be English.
360 * @param string $context
361 * The string context.
363 * @return string|false
364 * Translated string if there is a translation, FALSE if not.
366 public function translateString($name, $langcode, $source, $context) {
368 // If translations for a language have not been loaded yet.
369 if (!isset($this->translations[$name][$langcode])) {
370 // Preload all translations for this configuration name and language.
371 $this->translations[$name][$langcode] = [];
372 foreach ($this->localeStorage->getTranslations(['language' => $langcode, 'type' => 'configuration', 'name' => $name]) as $string) {
373 $this->translations[$name][$langcode][$string->context][$string->source] = $string;
376 if (!isset($this->translations[$name][$langcode][$context][$source])) {
377 // There is no translation of the source string in this config location
378 // to this language for this context.
379 if ($translation = $this->localeStorage->findTranslation(['source' => $source, 'context' => $context, 'language' => $langcode])) {
380 // Look for a translation of the string. It might have one, but not
381 // be saved in this configuration location yet.
382 // If the string has a translation for this context to this language,
383 // save it in the configuration location so it can be looked up faster
385 $this->localeStorage->createString((array) $translation)
386 ->addLocation('configuration', $name)
390 // No translation was found. Add the source to the configuration
391 // location so it can be translated, and the string is faster to look
393 $translation = $this->localeStorage
394 ->createString(['source' => $source, 'context' => $context])
395 ->addLocation('configuration', $name)
399 // Add an entry, either the translation found, or a blank string object
400 // to track the source string, to this configuration location, language,
402 $this->translations[$name][$langcode][$context][$source] = $translation;
405 // Return the string only when the string object had a translation.
406 if ($this->translations[$name][$langcode][$context][$source]->isTranslation()) {
407 return $this->translations[$name][$langcode][$context][$source]->getString();
414 * Reset static cache of configuration string translations.
418 public function reset() {
419 $this->translations = [];
424 * Get the translation object for the given source/context and language.
426 * @param string $name
427 * Name of the configuration location.
428 * @param string $langcode
429 * Language code to translate to.
430 * @param string $source
431 * The source string, should be English.
432 * @param string $context
433 * The string context.
435 * @return \Drupal\locale\TranslationString|false
436 * The translation object if the string was not empty or FALSE otherwise.
438 public function getStringTranslation($name, $langcode, $source, $context) {
440 $this->translateString($name, $langcode, $source, $context);
441 if ($string = $this->translations[$name][$langcode][$context][$source]) {
442 if (!$string->isTranslation()) {
443 $conditions = ['lid' => $string->lid, 'language' => $langcode];
444 $translation = $this->localeStorage->createTranslation($conditions);
445 $this->translations[$name][$langcode][$context][$source] = $translation;
457 * Checks whether a language has configuration translation.
459 * @param string $name
460 * Configuration name.
461 * @param string $langcode
465 * A boolean indicating if a language has configuration translations.
467 public function hasTranslation($name, $langcode) {
468 $translation = $this->languageManager->getLanguageConfigOverride($langcode, $name);
469 return !$translation->isNew();
473 * Returns the original language code for this shipped configuration.
475 * @param string $name
476 * The configuration name.
478 * @return null|string
479 * Language code of the default configuration for $name. If the default
480 * configuration data for $name did not contain a language code, it is
481 * assumed to be English. The return value is NULL if no such default
482 * configuration exists.
484 public function getDefaultConfigLangcode($name) {
485 // Config entities that do not have the 'default_config_hash' cannot be
486 // shipped configuration regardless of whether there is a name match.
487 // configurable_language entities are a special case since they can be
488 // translated regardless of whether they are shipped if they in the standard
490 $config_entity_type = $this->configManager->getEntityTypeIdByName($name);
491 if (!$config_entity_type || $config_entity_type === 'configurable_language'
492 || !empty($this->configFactory->get($name)->get('_core.default_config_hash'))
494 $shipped = $this->defaultConfigStorage->read($name);
495 if (!empty($shipped)) {
496 return !empty($shipped['langcode']) ? $shipped['langcode'] : 'en';
503 * Returns the current language code for this active configuration.
505 * @param string $name
506 * The configuration name.
508 * @return null|string
509 * Language code of the current active configuration for $name. If the
510 * configuration data for $name did not contain a language code, it is
511 * assumed to be English. The return value is NULL if no such active
512 * configuration exists.
514 public function getActiveConfigLangcode($name) {
515 $active = $this->configStorage->read($name);
516 if (!empty($active)) {
517 return !empty($active['langcode']) ? $active['langcode'] : 'en';
522 * Whether the given configuration is supported for interface translation.
524 * @param string $name
525 * The configuration name.
528 * TRUE if interface translation is supported.
530 public function isSupported($name) {
531 return $this->getDefaultConfigLangcode($name) == 'en' && $this->configStorage->read($name);
535 * Indicates whether configuration translations are being updated from locale.
538 * Whether or not configuration translations are currently being updated.
539 * If TRUE, LocaleConfigManager is in control of the process and the
540 * reference data is locale's storage. Changes made to active configuration
541 * and overrides in this case should not feed back to locale storage.
542 * On the other hand, when not updating from locale and configuration
543 * translations change, we need to feed back to the locale storage.
545 public function isUpdatingTranslationsFromLocale() {
546 return $this->isUpdatingFromLocale;
550 * Updates all configuration translations for the names / languages provided.
552 * To be used when interface translation changes result in the need to update
553 * configuration translations to keep them in sync.
555 * @param array $names
556 * Array of names of configuration objects to update.
557 * @param array $langcodes
558 * (optional) Array of language codes to update. Defaults to all
559 * configurable languages.
562 * Total number of configuration override and active configuration objects
563 * updated (saved or removed).
565 public function updateConfigTranslations(array $names, array $langcodes = []) {
566 $langcodes = $langcodes ? $langcodes : array_keys($this->languageManager->getLanguages());
568 foreach ($names as $name) {
569 $translatable = $this->getTranslatableDefaultConfig($name);
570 if (empty($translatable)) {
571 // If there is nothing translatable in this configuration or not
572 // supported, skip it.
576 $active_langcode = $this->getActiveConfigLangcode($name);
577 $active = $this->configStorage->read($name);
579 foreach ($langcodes as $langcode) {
580 $processed = $this->processTranslatableData($name, $active, $translatable, $langcode);
581 // If the language code is not the same as the active storage
582 // language, we should update the configuration override.
583 if ($langcode != $active_langcode) {
584 $override = $this->languageManager->getLanguageConfigOverride($langcode, $name);
585 // Filter out locale managed configuration keys so that translations
586 // removed from Locale will be reflected in the config override.
587 $data = $this->filterOverride($override->get(), $translatable);
588 if (!empty($processed)) {
589 // Merge in the Locale managed translations with existing data.
590 $data = NestedArray::mergeDeepArray([$data, $processed], TRUE);
592 if (empty($data) && !$override->isNew()) {
593 // The configuration override contains Locale overrides that no
595 $this->deleteTranslationOverride($name, $langcode);
598 elseif (!empty($data)) {
599 // Update translation data in configuration override.
600 $this->saveTranslationOverride($name, $langcode, $data);
604 elseif (locale_is_translatable($langcode)) {
605 // If the language code is the active storage language, we should
606 // update. If it is English, we should only update if English is also
608 $active = NestedArray::mergeDeepArray([$active, $processed], TRUE);
609 $this->saveTranslationActive($name, $active);
618 * Filters override data based on default translatable items.
620 * @param array $override_data
621 * Configuration override data.
622 * @param array $translatable
623 * Translatable data array. @see self::getTranslatableData()
625 * Nested array of any items of $override_data which did not have keys in
626 * $translatable. May be empty if $override_data only had items which were
627 * also in $translatable.
629 protected function filterOverride(array $override_data, array $translatable) {
631 foreach ($override_data as $key => $value) {
632 if (isset($translatable[$key])) {
633 // If the translatable default configuration has this key, look further
634 // for subkeys or ignore this element for scalar values.
635 if (is_array($value)) {
636 $value = $this->filterOverride($value, $translatable[$key]);
637 if (!empty($value)) {
638 $filtered_data[$key] = $value;
643 // If this key was not in the translatable default configuration,
645 $filtered_data[$key] = $value;
648 return $filtered_data;