Updated Drupal to 8.6. This goes with the following updates because it's possible...
[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       $typed_config = $this->typedConfigManager->createFromNameAndData($name, $data);
144       if ($typed_config instanceof TraversableTypedDataInterface) {
145         return $this->getTranslatableData($typed_config);
146       }
147     }
148     return [];
149   }
150
151   /**
152    * Gets translatable configuration data for a typed configuration element.
153    *
154    * @param \Drupal\Core\TypedData\TypedDataInterface $element
155    *   Typed configuration element.
156    *
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.
162    */
163   protected function getTranslatableData(TypedDataInterface $element) {
164     $translatable = [];
165     if ($element instanceof TraversableTypedDataInterface) {
166       foreach ($element as $key => $property) {
167         $value = $this->getTranslatableData($property);
168         if (!empty($value)) {
169           $translatable[$key] = $value;
170         }
171       }
172     }
173     else {
174       // Something is only translatable by Locale if there is a string in the
175       // first place.
176       $value = $element->getValue();
177       $definition = $element->getDataDefinition();
178       if (!empty($definition['translatable']) && $value !== '' && $value !== NULL) {
179         $options = [];
180         if (isset($definition['translation context'])) {
181           $options['context'] = $definition['translation context'];
182         }
183         return new TranslatableMarkup($value, [], $options);
184       }
185     }
186     return $translatable;
187   }
188
189   /**
190    * Process the translatable data array with a given language.
191    *
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.
196    *
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.
207    *
208    * @return array
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.
212    *
213    * @see self::getTranslatableData()
214    */
215   protected function processTranslatableData($name, array $active, array $translatable, $langcode) {
216     $translated = [];
217     foreach ($translatable as $key => $item) {
218       if (!isset($active[$key])) {
219         continue;
220       }
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;
226         }
227       }
228       else {
229         if (locale_is_translatable($langcode)) {
230           $value = $this->translateString($name, $langcode, $item->getUntranslatedString(), $item->getOption('context'));
231         }
232         else {
233           $value = $item->getUntranslatedString();
234         }
235         if (!empty($value)) {
236           $translated[$key] = $value;
237         }
238       }
239     }
240     return $translated;
241   }
242
243   /**
244    * Saves translated configuration override.
245    *
246    * @param string $name
247    *   Configuration object name.
248    * @param string $langcode
249    *   Language code.
250    * @param array $data
251    *   Configuration data to be saved, that will be only the translated values.
252    */
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;
257   }
258
259   /**
260    * Saves translated configuration data.
261    *
262    * @param string $name
263    *   Configuration object name.
264    * @param array $data
265    *   Configuration data to be saved with translations merged in.
266    */
267   protected function saveTranslationActive($name, array $data) {
268     $this->isUpdatingFromLocale = TRUE;
269     $this->configFactory->getEditable($name)->setData($data)->save();
270     $this->isUpdatingFromLocale = FALSE;
271   }
272
273   /**
274    * Deletes translated configuration data.
275    *
276    * @param string $name
277    *   Configuration object name.
278    * @param string $langcode
279    *   Language code.
280    */
281   protected function deleteTranslationOverride($name, $langcode) {
282     $this->isUpdatingFromLocale = TRUE;
283     $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
284     $this->isUpdatingFromLocale = FALSE;
285   }
286
287   /**
288    * Gets configuration names associated with components.
289    *
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.
293    *
294    * @return array
295    *   Array of configuration object names.
296    */
297   public function getComponentNames(array $components = []) {
298     $components = array_filter($components);
299     if ($components) {
300       $names = [];
301       foreach ($components as $type => $list) {
302         // InstallStorage::getComponentNames returns a list of folders keyed by
303         // config name.
304         $names = array_merge($names, $this->defaultConfigStorage->getComponentNames($type, $list));
305       }
306       return $names;
307     }
308     else {
309       return $this->defaultConfigStorage->listAll();
310     }
311   }
312
313   /**
314    * Gets configuration names associated with strings.
315    *
316    * @param array $lids
317    *   Array with string identifiers.
318    *
319    * @return array
320    *   Array of configuration object names.
321    */
322   public function getStringNames(array $lids) {
323     $names = [];
324     $locations = $this->localeStorage->getLocations(['sid' => $lids, 'type' => 'configuration']);
325     foreach ($locations as $location) {
326       $names[$location->name] = $location->name;
327     }
328     return $names;
329   }
330
331   /**
332    * Deletes configuration for language.
333    *
334    * @param string $langcode
335    *   Language code to delete.
336    */
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();
342     }
343     $this->isUpdatingFromLocale = FALSE;
344   }
345
346   /**
347    * Translates string using the localization system.
348    *
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.
353    *
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.
362    *
363    * @return string|false
364    *   Translated string if there is a translation, FALSE if not.
365    */
366   public function translateString($name, $langcode, $source, $context) {
367     if ($source) {
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;
374         }
375       }
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
384           // next time.
385           $this->localeStorage->createString((array) $translation)
386             ->addLocation('configuration', $name)
387             ->save();
388         }
389         else {
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
392           // for next time.
393           $translation = $this->localeStorage
394             ->createString(['source' => $source, 'context' => $context])
395             ->addLocation('configuration', $name)
396             ->save();
397         }
398
399         // Add an entry, either the translation found, or a blank string object
400         // to track the source string, to this configuration location, language,
401         // and context.
402         $this->translations[$name][$langcode][$context][$source] = $translation;
403       }
404
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();
408       }
409     }
410     return FALSE;
411   }
412
413   /**
414    * Reset static cache of configuration string translations.
415    *
416    * @return $this
417    */
418   public function reset() {
419     $this->translations = [];
420     return $this;
421   }
422
423   /**
424    * Get the translation object for the given source/context and language.
425    *
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.
434    *
435    * @return \Drupal\locale\TranslationString|false
436    *   The translation object if the string was not empty or FALSE otherwise.
437    */
438   public function getStringTranslation($name, $langcode, $source, $context) {
439     if ($source) {
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;
446           return $translation;
447         }
448         else {
449           return $string;
450         }
451       }
452     }
453     return FALSE;
454   }
455
456   /**
457    * Checks whether a language has configuration translation.
458    *
459    * @param string $name
460    *   Configuration name.
461    * @param string $langcode
462    *   A language code.
463    *
464    * @return bool
465    *   A boolean indicating if a language has configuration translations.
466    */
467   public function hasTranslation($name, $langcode) {
468     $translation = $this->languageManager->getLanguageConfigOverride($langcode, $name);
469     return !$translation->isNew();
470   }
471
472   /**
473    * Returns the original language code for this shipped configuration.
474    *
475    * @param string $name
476    *   The configuration name.
477    *
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.
483    */
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
489     // language list.
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'))
493     ) {
494       $shipped = $this->defaultConfigStorage->read($name);
495       if (!empty($shipped)) {
496         return !empty($shipped['langcode']) ? $shipped['langcode'] : 'en';
497       }
498     }
499     return NULL;
500   }
501
502   /**
503    * Returns the current language code for this active configuration.
504    *
505    * @param string $name
506    *   The configuration name.
507    *
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.
513    */
514   public function getActiveConfigLangcode($name) {
515     $active = $this->configStorage->read($name);
516     if (!empty($active)) {
517       return !empty($active['langcode']) ? $active['langcode'] : 'en';
518     }
519   }
520
521   /**
522    * Whether the given configuration is supported for interface translation.
523    *
524    * @param string $name
525    *   The configuration name.
526    *
527    * @return bool
528    *   TRUE if interface translation is supported.
529    */
530   public function isSupported($name) {
531     return $this->getDefaultConfigLangcode($name) == 'en' && $this->configStorage->read($name);
532   }
533
534   /**
535    * Indicates whether configuration translations are being updated from locale.
536    *
537    * @return bool
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.
544    */
545   public function isUpdatingTranslationsFromLocale() {
546     return $this->isUpdatingFromLocale;
547   }
548
549   /**
550    * Updates all configuration translations for the names / languages provided.
551    *
552    * To be used when interface translation changes result in the need to update
553    * configuration translations to keep them in sync.
554    *
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.
560    *
561    * @return int
562    *   Total number of configuration override and active configuration objects
563    *   updated (saved or removed).
564    */
565   public function updateConfigTranslations(array $names, array $langcodes = []) {
566     $langcodes = $langcodes ? $langcodes : array_keys($this->languageManager->getLanguages());
567     $count = 0;
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.
573         continue;
574       }
575
576       $active_langcode = $this->getActiveConfigLangcode($name);
577       $active = $this->configStorage->read($name);
578
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);
591           }
592           if (empty($data) && !$override->isNew()) {
593             // The configuration override contains Locale overrides that no
594             // longer exist.
595             $this->deleteTranslationOverride($name, $langcode);
596             $count++;
597           }
598           elseif (!empty($data)) {
599             // Update translation data in configuration override.
600             $this->saveTranslationOverride($name, $langcode, $data);
601             $count++;
602           }
603         }
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
607           // translatable.
608           $active = NestedArray::mergeDeepArray([$active, $processed], TRUE);
609           $this->saveTranslationActive($name, $active);
610           $count++;
611         }
612       }
613     }
614     return $count;
615   }
616
617   /**
618    * Filters override data based on default translatable items.
619    *
620    * @param array $override_data
621    *   Configuration override data.
622    * @param array $translatable
623    *   Translatable data array. @see self::getTranslatableData()
624    * @return array
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.
628    */
629   protected function filterOverride(array $override_data, array $translatable) {
630     $filtered_data = [];
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;
639           }
640         }
641       }
642       else {
643         // If this key was not in the translatable default configuration,
644         // keep it.
645         $filtered_data[$key] = $value;
646       }
647     }
648     return $filtered_data;
649   }
650
651 }