Version 1
[yaffs-website] / web / core / modules / locale / src / LocaleConfigManager.php
1 <?php
2
3 namespace Drupal\locale;
4
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;
14
15 /**
16  * Manages configuration supported in part by interface translation.
17  *
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
24  * override.
25  *
26  * In turn when translated configuration or configuration language overrides are
27  * changed, it is the responsibility of LocaleConfigSubscriber to update locale
28  * storage.
29  *
30  * By design locale module only deals with sources in English.
31  *
32  * @see \Drupal\locale\LocaleConfigSubscriber
33  */
34 class LocaleConfigManager {
35
36   /**
37    * The storage instance for reading configuration data.
38    *
39    * @var \Drupal\Core\Config\StorageInterface
40    */
41   protected $configStorage;
42
43   /**
44    * The string storage for reading and writing translations.
45    *
46    * @var \Drupal\locale\StringStorageInterface;
47    */
48   protected $localeStorage;
49
50   /**
51    * Array with preloaded string translations.
52    *
53    * @var array
54    */
55   protected $translations;
56
57   /**
58    * The configuration factory.
59    *
60    * @var \Drupal\Core\Config\ConfigFactoryInterface
61    */
62   protected $configFactory;
63
64   /**
65    * The language manager.
66    *
67    * @var \Drupal\language\ConfigurableLanguageManagerInterface
68    */
69   protected $languageManager;
70
71   /**
72    * The typed config manager.
73    *
74    * @var \Drupal\Core\Config\TypedConfigManagerInterface
75    */
76   protected $typedConfigManager;
77
78   /**
79    * Whether or not configuration translations are being updated from locale.
80    *
81    * @see self::isUpdatingFromLocale()
82    *
83    * @var bool
84    */
85   protected $isUpdatingFromLocale = FALSE;
86
87   /**
88    * The locale default config storage instance.
89    *
90    * @var \Drupal\locale\LocaleDefaultConfigStorage
91    */
92   protected $defaultConfigStorage;
93
94   /**
95    * The configuration manager.
96    *
97    * @var \Drupal\Core\Config\ConfigManagerInterface
98    */
99   protected $configManager;
100
101   /**
102    * Creates a new typed configuration manager.
103    *
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.
118    */
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;
127   }
128
129   /**
130    * Gets array of translated strings for Locale translatable configuration.
131    *
132    * @param string $name
133    *   Configuration object name.
134    *
135    * @return array
136    *   Array of Locale translatable elements of the default configuration in
137    *   $name.
138    */
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);
148       }
149     }
150     return [];
151   }
152
153   /**
154    * Gets translatable configuration data for a typed configuration element.
155    *
156    * @param \Drupal\Core\TypedData\TypedDataInterface $element
157    *   Typed configuration element.
158    *
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.
164    */
165   protected function getTranslatableData(TypedDataInterface $element) {
166     $translatable = [];
167     if ($element instanceof TraversableTypedDataInterface) {
168       foreach ($element as $key => $property) {
169         $value = $this->getTranslatableData($property);
170         if (!empty($value)) {
171           $translatable[$key] = $value;
172         }
173       }
174     }
175     else {
176       // Something is only translatable by Locale if there is a string in the
177       // first place.
178       $value = $element->getValue();
179       $definition = $element->getDataDefinition();
180       if (!empty($definition['translatable']) && $value !== '' && $value !== NULL) {
181         $options = [];
182         if (isset($definition['translation context'])) {
183           $options['context'] = $definition['translation context'];
184         }
185         return new TranslatableMarkup($value, [], $options);
186       }
187     }
188     return $translatable;
189   }
190
191   /**
192    * Process the translatable data array with a given language.
193    *
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.
198    *
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.
209    *
210    * @return array
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.
214    *
215    * @see self::getTranslatableData()
216    */
217   protected function processTranslatableData($name, array $active, array $translatable, $langcode) {
218     $translated = [];
219     foreach ($translatable as $key => $item) {
220       if (!isset($active[$key])) {
221         continue;
222       }
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;
228         }
229       }
230       else {
231         if (locale_is_translatable($langcode)) {
232           $value = $this->translateString($name, $langcode, $item->getUntranslatedString(), $item->getOption('context'));
233         }
234         else {
235           $value = $item->getUntranslatedString();
236         }
237         if (!empty($value)) {
238           $translated[$key] = $value;
239         }
240       }
241     }
242     return $translated;
243   }
244
245   /**
246    * Saves translated configuration override.
247    *
248    * @param string $name
249    *   Configuration object name.
250    * @param string $langcode
251    *   Language code.
252    * @param array $data
253    *   Configuration data to be saved, that will be only the translated values.
254    */
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;
259   }
260
261   /**
262    * Saves translated configuration data.
263    *
264    * @param string $name
265    *   Configuration object name.
266    * @param array $data
267    *   Configuration data to be saved with translations merged in.
268    */
269   protected function saveTranslationActive($name, array $data) {
270     $this->isUpdatingFromLocale = TRUE;
271     $this->configFactory->getEditable($name)->setData($data)->save();
272     $this->isUpdatingFromLocale = FALSE;
273   }
274
275   /**
276    * Deletes translated configuration data.
277    *
278    * @param string $name
279    *   Configuration object name.
280    * @param string $langcode
281    *   Language code.
282    */
283   protected function deleteTranslationOverride($name, $langcode) {
284     $this->isUpdatingFromLocale = TRUE;
285     $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
286     $this->isUpdatingFromLocale = FALSE;
287   }
288
289   /**
290    * Gets configuration names associated with components.
291    *
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.
295    *
296    * @return array
297    *   Array of configuration object names.
298    */
299   public function getComponentNames(array $components = []) {
300     $components = array_filter($components);
301     if ($components) {
302       $names = [];
303       foreach ($components as $type => $list) {
304         // InstallStorage::getComponentNames returns a list of folders keyed by
305         // config name.
306         $names = array_merge($names, $this->defaultConfigStorage->getComponentNames($type, $list));
307       }
308       return $names;
309     }
310     else {
311       return $this->defaultConfigStorage->listAll();
312     }
313   }
314
315   /**
316    * Gets configuration names associated with strings.
317    *
318    * @param array $lids
319    *   Array with string identifiers.
320    *
321    * @return array
322    *   Array of configuration object names.
323    */
324   public function getStringNames(array $lids) {
325     $names = [];
326     $locations = $this->localeStorage->getLocations(['sid' => $lids, 'type' => 'configuration']);
327     foreach ($locations as $location) {
328       $names[$location->name] = $location->name;
329     }
330     return $names;
331   }
332
333   /**
334    * Deletes configuration for language.
335    *
336    * @param string $langcode
337    *   Language code to delete.
338    */
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();
344     }
345     $this->isUpdatingFromLocale = FALSE;
346   }
347
348   /**
349    * Translates string using the localization system.
350    *
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.
355    *
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.
364    *
365    * @return string|false
366    *   Translated string if there is a translation, FALSE if not.
367    */
368   public function translateString($name, $langcode, $source, $context) {
369     if ($source) {
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;
376         }
377       }
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
386           // next time.
387           $this->localeStorage->createString((array) $translation)
388             ->addLocation('configuration', $name)
389             ->save();
390         }
391         else {
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
394           // for next time.
395           $translation = $this->localeStorage
396             ->createString(['source' => $source, 'context' => $context])
397             ->addLocation('configuration', $name)
398             ->save();
399         }
400
401         // Add an entry, either the translation found, or a blank string object
402         // to track the source string, to this configuration location, language,
403         // and context.
404         $this->translations[$name][$langcode][$context][$source] = $translation;
405       }
406
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();
410       }
411     }
412     return FALSE;
413   }
414
415   /**
416    * Reset static cache of configuration string translations.
417    *
418    * @return $this
419    */
420   public function reset() {
421     $this->translations = [];
422     return $this;
423   }
424
425   /**
426    * Get the translation object for the given source/context and language.
427    *
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.
436    *
437    * @return \Drupal\locale\TranslationString|false
438    *   The translation object if the string was not empty or FALSE otherwise.
439    */
440   public function getStringTranslation($name, $langcode, $source, $context) {
441     if ($source) {
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;
448           return $translation;
449         }
450         else {
451           return $string;
452         }
453       }
454     }
455     return FALSE;
456   }
457
458   /**
459    * Checks whether a language has configuration translation.
460    *
461    * @param string $name
462    *   Configuration name.
463    * @param string $langcode
464    *   A language code.
465    *
466    * @return bool
467    *   A boolean indicating if a language has configuration translations.
468    */
469   public function hasTranslation($name, $langcode) {
470     $translation = $this->languageManager->getLanguageConfigOverride($langcode, $name);
471     return !$translation->isNew();
472   }
473
474   /**
475    * Returns the original language code for this shipped configuration.
476    *
477    * @param string $name
478    *   The configuration name.
479    *
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.
485    */
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
491     // language list.
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'))
495     ) {
496       $shipped = $this->defaultConfigStorage->read($name);
497       if (!empty($shipped)) {
498         return !empty($shipped['langcode']) ? $shipped['langcode'] : 'en';
499       }
500     }
501     return NULL;
502   }
503
504   /**
505    * Returns the current language code for this active configuration.
506    *
507    * @param string $name
508    *   The configuration name.
509    *
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.
515    */
516   public function getActiveConfigLangcode($name) {
517     $active = $this->configStorage->read($name);
518     if (!empty($active)) {
519       return !empty($active['langcode']) ? $active['langcode'] : 'en';
520     }
521   }
522
523   /**
524    * Whether the given configuration is supported for interface translation.
525    *
526    * @param string $name
527    *   The configuration name.
528    *
529    * @return bool
530    *   TRUE if interface translation is supported.
531    */
532   public function isSupported($name) {
533     return $this->getDefaultConfigLangcode($name) == 'en' && $this->configStorage->read($name);
534   }
535
536   /**
537    * Indicates whether configuration translations are being updated from locale.
538    *
539    * @return bool
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.
546    */
547   public function isUpdatingTranslationsFromLocale() {
548     return $this->isUpdatingFromLocale;
549   }
550
551   /**
552    * Updates all configuration translations for the names / languages provided.
553    *
554    * To be used when interface translation changes result in the need to update
555    * configuration translations to keep them in sync.
556    *
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.
562    *
563    * @return int
564    *   Total number of configuration override and active configuration objects
565    *   updated (saved or removed).
566    */
567   public function updateConfigTranslations(array $names, array $langcodes = []) {
568     $langcodes = $langcodes ? $langcodes : array_keys($this->languageManager->getLanguages());
569     $count = 0;
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.
575         continue;
576       }
577
578       $active_langcode = $this->getActiveConfigLangcode($name);
579       $active = $this->configStorage->read($name);
580
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);
593           }
594           if (empty($data) && !$override->isNew()) {
595             // The configuration override contains Locale overrides that no
596             // longer exist.
597             $this->deleteTranslationOverride($name, $langcode);
598             $count++;
599           }
600           elseif (!empty($data)) {
601             // Update translation data in configuration override.
602             $this->saveTranslationOverride($name, $langcode, $data);
603             $count++;
604           }
605         }
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
609           // translatable.
610           $active = NestedArray::mergeDeepArray([$active, $processed], TRUE);
611           $this->saveTranslationActive($name, $active);
612           $count++;
613         }
614       }
615     }
616     return $count;
617   }
618
619   /**
620    * Filters override data based on default translatable items.
621    *
622    * @param array $override_data
623    *   Configuration override data.
624    * @param array $translatable
625    *   Translatable data array. @see self::getTranslatableData()
626    * @return array
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.
630    */
631   protected function filterOverride(array $override_data, array $translatable) {
632     $filtered_data = [];
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;
641           }
642         }
643       }
644       else {
645         // If this key was not in the translatable default configuration,
646         // keep it.
647         $filtered_data[$key] = $value;
648       }
649     }
650     return $filtered_data;
651   }
652
653 }