LocaleConfigManager.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. <?php
  2. namespace Drupal\locale;
  3. use Drupal\Component\Utility\NestedArray;
  4. use Drupal\Core\Config\ConfigFactoryInterface;
  5. use Drupal\Core\Config\ConfigManagerInterface;
  6. use Drupal\Core\Config\StorageInterface;
  7. use Drupal\Core\Config\TypedConfigManagerInterface;
  8. use Drupal\Core\StringTranslation\TranslatableMarkup;
  9. use Drupal\Core\TypedData\TraversableTypedDataInterface;
  10. use Drupal\Core\TypedData\TypedDataInterface;
  11. use Drupal\language\ConfigurableLanguageManagerInterface;
  12. /**
  13. * Manages configuration supported in part by interface translation.
  14. *
  15. * This manager is responsible to update configuration overrides and active
  16. * translations when interface translation data changes. This allows Drupal to
  17. * translate user roles, views, blocks, etc. after Drupal has been installed
  18. * using the locale module's storage. When translations change in locale,
  19. * LocaleConfigManager::updateConfigTranslations() is invoked to update the
  20. * corresponding storage of the translation in the original config object or an
  21. * override.
  22. *
  23. * In turn when translated configuration or configuration language overrides are
  24. * changed, it is the responsibility of LocaleConfigSubscriber to update locale
  25. * storage.
  26. *
  27. * By design locale module only deals with sources in English.
  28. *
  29. * @see \Drupal\locale\LocaleConfigSubscriber
  30. */
  31. class LocaleConfigManager {
  32. /**
  33. * The storage instance for reading configuration data.
  34. *
  35. * @var \Drupal\Core\Config\StorageInterface
  36. */
  37. protected $configStorage;
  38. /**
  39. * The string storage for reading and writing translations.
  40. *
  41. * @var \Drupal\locale\StringStorageInterface
  42. */
  43. protected $localeStorage;
  44. /**
  45. * Array with preloaded string translations.
  46. *
  47. * @var array
  48. */
  49. protected $translations;
  50. /**
  51. * The configuration factory.
  52. *
  53. * @var \Drupal\Core\Config\ConfigFactoryInterface
  54. */
  55. protected $configFactory;
  56. /**
  57. * The language manager.
  58. *
  59. * @var \Drupal\language\ConfigurableLanguageManagerInterface
  60. */
  61. protected $languageManager;
  62. /**
  63. * The typed config manager.
  64. *
  65. * @var \Drupal\Core\Config\TypedConfigManagerInterface
  66. */
  67. protected $typedConfigManager;
  68. /**
  69. * Whether or not configuration translations are being updated from locale.
  70. *
  71. * @see self::isUpdatingFromLocale()
  72. *
  73. * @var bool
  74. */
  75. protected $isUpdatingFromLocale = FALSE;
  76. /**
  77. * The locale default config storage instance.
  78. *
  79. * @var \Drupal\locale\LocaleDefaultConfigStorage
  80. */
  81. protected $defaultConfigStorage;
  82. /**
  83. * The configuration manager.
  84. *
  85. * @var \Drupal\Core\Config\ConfigManagerInterface
  86. */
  87. protected $configManager;
  88. /**
  89. * Creates a new typed configuration manager.
  90. *
  91. * @param \Drupal\Core\Config\StorageInterface $config_storage
  92. * The storage object to use for reading configuration data.
  93. * @param \Drupal\locale\StringStorageInterface $locale_storage
  94. * The locale storage to use for reading string translations.
  95. * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
  96. * The configuration factory
  97. * @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
  98. * The typed configuration manager.
  99. * @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager
  100. * The language manager.
  101. * @param \Drupal\locale\LocaleDefaultConfigStorage $default_config_storage
  102. * The locale default configuration storage.
  103. * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
  104. * The configuration manager.
  105. */
  106. 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) {
  107. $this->configStorage = $config_storage;
  108. $this->localeStorage = $locale_storage;
  109. $this->configFactory = $config_factory;
  110. $this->typedConfigManager = $typed_config;
  111. $this->languageManager = $language_manager;
  112. $this->defaultConfigStorage = $default_config_storage;
  113. $this->configManager = $config_manager;
  114. }
  115. /**
  116. * Gets array of translated strings for Locale translatable configuration.
  117. *
  118. * @param string $name
  119. * Configuration object name.
  120. *
  121. * @return array
  122. * Array of Locale translatable elements of the default configuration in
  123. * $name.
  124. */
  125. public function getTranslatableDefaultConfig($name) {
  126. if ($this->isSupported($name)) {
  127. // Create typed configuration wrapper based on install storage data.
  128. $data = $this->defaultConfigStorage->read($name);
  129. $typed_config = $this->typedConfigManager->createFromNameAndData($name, $data);
  130. if ($typed_config instanceof TraversableTypedDataInterface) {
  131. return $this->getTranslatableData($typed_config);
  132. }
  133. }
  134. return [];
  135. }
  136. /**
  137. * Gets translatable configuration data for a typed configuration element.
  138. *
  139. * @param \Drupal\Core\TypedData\TypedDataInterface $element
  140. * Typed configuration element.
  141. *
  142. * @return array|\Drupal\Core\StringTranslation\TranslatableMarkup
  143. * A nested array matching the exact structure under $element with only the
  144. * elements that are translatable wrapped into a TranslatableMarkup. If the
  145. * provided $element is not traversable, the return value is a single
  146. * TranslatableMarkup.
  147. */
  148. protected function getTranslatableData(TypedDataInterface $element) {
  149. $translatable = [];
  150. if ($element instanceof TraversableTypedDataInterface) {
  151. foreach ($element as $key => $property) {
  152. $value = $this->getTranslatableData($property);
  153. if (!empty($value)) {
  154. $translatable[$key] = $value;
  155. }
  156. }
  157. }
  158. else {
  159. // Something is only translatable by Locale if there is a string in the
  160. // first place.
  161. $value = $element->getValue();
  162. $definition = $element->getDataDefinition();
  163. if (!empty($definition['translatable']) && $value !== '' && $value !== NULL) {
  164. $options = [];
  165. if (isset($definition['translation context'])) {
  166. $options['context'] = $definition['translation context'];
  167. }
  168. return new TranslatableMarkup($value, [], $options);
  169. }
  170. }
  171. return $translatable;
  172. }
  173. /**
  174. * Process the translatable data array with a given language.
  175. *
  176. * If the given language is translatable, will return the translated copy
  177. * which will only contain strings that had translations. If the given
  178. * language is English and is not translatable, will return a simplified
  179. * array of the English source strings only.
  180. *
  181. * @param string $name
  182. * The configuration name.
  183. * @param array $active
  184. * The active configuration data.
  185. * @param array|\Drupal\Core\StringTranslation\TranslatableMarkup[] $translatable
  186. * The translatable array structure. A nested array matching the exact
  187. * structure under of the default configuration for $name with only the
  188. * elements that are translatable wrapped into a TranslatableMarkup.
  189. * @param string $langcode
  190. * The language code to process the array with.
  191. *
  192. * @return array
  193. * Processed translatable data array. Will only contain translations
  194. * different from source strings or in case of untranslatable English, the
  195. * source strings themselves.
  196. *
  197. * @see self::getTranslatableData()
  198. */
  199. protected function processTranslatableData($name, array $active, array $translatable, $langcode) {
  200. $translated = [];
  201. foreach ($translatable as $key => $item) {
  202. if (!isset($active[$key])) {
  203. continue;
  204. }
  205. if (is_array($item)) {
  206. // Only add this key if there was a translated value underneath.
  207. $value = $this->processTranslatableData($name, $active[$key], $item, $langcode);
  208. if (!empty($value)) {
  209. $translated[$key] = $value;
  210. }
  211. }
  212. else {
  213. if (locale_is_translatable($langcode)) {
  214. $value = $this->translateString($name, $langcode, $item->getUntranslatedString(), $item->getOption('context'));
  215. }
  216. else {
  217. $value = $item->getUntranslatedString();
  218. }
  219. if (!empty($value)) {
  220. $translated[$key] = $value;
  221. }
  222. }
  223. }
  224. return $translated;
  225. }
  226. /**
  227. * Saves translated configuration override.
  228. *
  229. * @param string $name
  230. * Configuration object name.
  231. * @param string $langcode
  232. * Language code.
  233. * @param array $data
  234. * Configuration data to be saved, that will be only the translated values.
  235. */
  236. protected function saveTranslationOverride($name, $langcode, array $data) {
  237. $this->isUpdatingFromLocale = TRUE;
  238. $this->languageManager->getLanguageConfigOverride($langcode, $name)->setData($data)->save();
  239. $this->isUpdatingFromLocale = FALSE;
  240. }
  241. /**
  242. * Saves translated configuration data.
  243. *
  244. * @param string $name
  245. * Configuration object name.
  246. * @param array $data
  247. * Configuration data to be saved with translations merged in.
  248. */
  249. protected function saveTranslationActive($name, array $data) {
  250. $this->isUpdatingFromLocale = TRUE;
  251. $this->configFactory->getEditable($name)->setData($data)->save();
  252. $this->isUpdatingFromLocale = FALSE;
  253. }
  254. /**
  255. * Deletes translated configuration data.
  256. *
  257. * @param string $name
  258. * Configuration object name.
  259. * @param string $langcode
  260. * Language code.
  261. */
  262. protected function deleteTranslationOverride($name, $langcode) {
  263. $this->isUpdatingFromLocale = TRUE;
  264. $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
  265. $this->isUpdatingFromLocale = FALSE;
  266. }
  267. /**
  268. * Gets configuration names associated with components.
  269. *
  270. * @param array $components
  271. * (optional) Array of component lists indexed by type. If not present or it
  272. * is an empty array, it will update all components.
  273. *
  274. * @return array
  275. * Array of configuration object names.
  276. */
  277. public function getComponentNames(array $components = []) {
  278. $components = array_filter($components);
  279. if ($components) {
  280. $names = [];
  281. foreach ($components as $type => $list) {
  282. // InstallStorage::getComponentNames returns a list of folders keyed by
  283. // config name.
  284. $names = array_merge($names, $this->defaultConfigStorage->getComponentNames($type, $list));
  285. }
  286. return $names;
  287. }
  288. else {
  289. return $this->defaultConfigStorage->listAll();
  290. }
  291. }
  292. /**
  293. * Gets configuration names associated with strings.
  294. *
  295. * @param array $lids
  296. * Array with string identifiers.
  297. *
  298. * @return array
  299. * Array of configuration object names.
  300. */
  301. public function getStringNames(array $lids) {
  302. $names = [];
  303. $locations = $this->localeStorage->getLocations(['sid' => $lids, 'type' => 'configuration']);
  304. foreach ($locations as $location) {
  305. $names[$location->name] = $location->name;
  306. }
  307. return $names;
  308. }
  309. /**
  310. * Deletes configuration for language.
  311. *
  312. * @param string $langcode
  313. * Language code to delete.
  314. */
  315. public function deleteLanguageTranslations($langcode) {
  316. $this->isUpdatingFromLocale = TRUE;
  317. $storage = $this->languageManager->getLanguageConfigOverrideStorage($langcode);
  318. foreach ($storage->listAll() as $name) {
  319. $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
  320. }
  321. $this->isUpdatingFromLocale = FALSE;
  322. }
  323. /**
  324. * Translates string using the localization system.
  325. *
  326. * So far we only know how to translate strings from English so the source
  327. * string should be in English.
  328. * Unlike regular t() translations, strings will be added to the source
  329. * tables only if this is marked as default data.
  330. *
  331. * @param string $name
  332. * Name of the configuration location.
  333. * @param string $langcode
  334. * Language code to translate to.
  335. * @param string $source
  336. * The source string, should be English.
  337. * @param string $context
  338. * The string context.
  339. *
  340. * @return string|false
  341. * Translated string if there is a translation, FALSE if not.
  342. */
  343. public function translateString($name, $langcode, $source, $context) {
  344. if ($source) {
  345. // If translations for a language have not been loaded yet.
  346. if (!isset($this->translations[$name][$langcode])) {
  347. // Preload all translations for this configuration name and language.
  348. $this->translations[$name][$langcode] = [];
  349. foreach ($this->localeStorage->getTranslations(['language' => $langcode, 'type' => 'configuration', 'name' => $name]) as $string) {
  350. $this->translations[$name][$langcode][$string->context][$string->source] = $string;
  351. }
  352. }
  353. if (!isset($this->translations[$name][$langcode][$context][$source])) {
  354. // There is no translation of the source string in this config location
  355. // to this language for this context.
  356. if ($translation = $this->localeStorage->findTranslation(['source' => $source, 'context' => $context, 'language' => $langcode])) {
  357. // Look for a translation of the string. It might have one, but not
  358. // be saved in this configuration location yet.
  359. // If the string has a translation for this context to this language,
  360. // save it in the configuration location so it can be looked up faster
  361. // next time.
  362. $this->localeStorage->createString((array) $translation)
  363. ->addLocation('configuration', $name)
  364. ->save();
  365. }
  366. else {
  367. // No translation was found. Add the source to the configuration
  368. // location so it can be translated, and the string is faster to look
  369. // for next time.
  370. $translation = $this->localeStorage
  371. ->createString(['source' => $source, 'context' => $context])
  372. ->addLocation('configuration', $name)
  373. ->save();
  374. }
  375. // Add an entry, either the translation found, or a blank string object
  376. // to track the source string, to this configuration location, language,
  377. // and context.
  378. $this->translations[$name][$langcode][$context][$source] = $translation;
  379. }
  380. // Return the string only when the string object had a translation.
  381. if ($this->translations[$name][$langcode][$context][$source]->isTranslation()) {
  382. return $this->translations[$name][$langcode][$context][$source]->getString();
  383. }
  384. }
  385. return FALSE;
  386. }
  387. /**
  388. * Reset static cache of configuration string translations.
  389. *
  390. * @return $this
  391. */
  392. public function reset() {
  393. $this->translations = [];
  394. return $this;
  395. }
  396. /**
  397. * Get the translation object for the given source/context and language.
  398. *
  399. * @param string $name
  400. * Name of the configuration location.
  401. * @param string $langcode
  402. * Language code to translate to.
  403. * @param string $source
  404. * The source string, should be English.
  405. * @param string $context
  406. * The string context.
  407. *
  408. * @return \Drupal\locale\TranslationString|false
  409. * The translation object if the string was not empty or FALSE otherwise.
  410. */
  411. public function getStringTranslation($name, $langcode, $source, $context) {
  412. if ($source) {
  413. $this->translateString($name, $langcode, $source, $context);
  414. if ($string = $this->translations[$name][$langcode][$context][$source]) {
  415. if (!$string->isTranslation()) {
  416. $conditions = ['lid' => $string->lid, 'language' => $langcode];
  417. $translation = $this->localeStorage->createTranslation($conditions);
  418. $this->translations[$name][$langcode][$context][$source] = $translation;
  419. return $translation;
  420. }
  421. else {
  422. return $string;
  423. }
  424. }
  425. }
  426. return FALSE;
  427. }
  428. /**
  429. * Checks whether a language has configuration translation.
  430. *
  431. * @param string $name
  432. * Configuration name.
  433. * @param string $langcode
  434. * A language code.
  435. *
  436. * @return bool
  437. * A boolean indicating if a language has configuration translations.
  438. */
  439. public function hasTranslation($name, $langcode) {
  440. $translation = $this->languageManager->getLanguageConfigOverride($langcode, $name);
  441. return !$translation->isNew();
  442. }
  443. /**
  444. * Returns the original language code for this shipped configuration.
  445. *
  446. * @param string $name
  447. * The configuration name.
  448. *
  449. * @return null|string
  450. * Language code of the default configuration for $name. If the default
  451. * configuration data for $name did not contain a language code, it is
  452. * assumed to be English. The return value is NULL if no such default
  453. * configuration exists.
  454. */
  455. public function getDefaultConfigLangcode($name) {
  456. // Config entities that do not have the 'default_config_hash' cannot be
  457. // shipped configuration regardless of whether there is a name match.
  458. // configurable_language entities are a special case since they can be
  459. // translated regardless of whether they are shipped if they in the standard
  460. // language list.
  461. $config_entity_type = $this->configManager->getEntityTypeIdByName($name);
  462. if (!$config_entity_type || $config_entity_type === 'configurable_language'
  463. || !empty($this->configFactory->get($name)->get('_core.default_config_hash'))
  464. ) {
  465. $shipped = $this->defaultConfigStorage->read($name);
  466. if (!empty($shipped)) {
  467. return !empty($shipped['langcode']) ? $shipped['langcode'] : 'en';
  468. }
  469. }
  470. return NULL;
  471. }
  472. /**
  473. * Returns the current language code for this active configuration.
  474. *
  475. * @param string $name
  476. * The configuration name.
  477. *
  478. * @return null|string
  479. * Language code of the current active configuration for $name. If the
  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 active
  482. * configuration exists.
  483. */
  484. public function getActiveConfigLangcode($name) {
  485. $active = $this->configStorage->read($name);
  486. if (!empty($active)) {
  487. return !empty($active['langcode']) ? $active['langcode'] : 'en';
  488. }
  489. }
  490. /**
  491. * Whether the given configuration is supported for interface translation.
  492. *
  493. * @param string $name
  494. * The configuration name.
  495. *
  496. * @return bool
  497. * TRUE if interface translation is supported.
  498. */
  499. public function isSupported($name) {
  500. return $this->getDefaultConfigLangcode($name) == 'en' && $this->configStorage->read($name);
  501. }
  502. /**
  503. * Indicates whether configuration translations are being updated from locale.
  504. *
  505. * @return bool
  506. * Whether or not configuration translations are currently being updated.
  507. * If TRUE, LocaleConfigManager is in control of the process and the
  508. * reference data is locale's storage. Changes made to active configuration
  509. * and overrides in this case should not feed back to locale storage.
  510. * On the other hand, when not updating from locale and configuration
  511. * translations change, we need to feed back to the locale storage.
  512. */
  513. public function isUpdatingTranslationsFromLocale() {
  514. return $this->isUpdatingFromLocale;
  515. }
  516. /**
  517. * Updates all configuration translations for the names / languages provided.
  518. *
  519. * To be used when interface translation changes result in the need to update
  520. * configuration translations to keep them in sync.
  521. *
  522. * @param array $names
  523. * Array of names of configuration objects to update.
  524. * @param array $langcodes
  525. * (optional) Array of language codes to update. Defaults to all
  526. * configurable languages.
  527. *
  528. * @return int
  529. * Total number of configuration override and active configuration objects
  530. * updated (saved or removed).
  531. */
  532. public function updateConfigTranslations(array $names, array $langcodes = []) {
  533. $langcodes = $langcodes ? $langcodes : array_keys($this->languageManager->getLanguages());
  534. $count = 0;
  535. foreach ($names as $name) {
  536. $translatable = $this->getTranslatableDefaultConfig($name);
  537. if (empty($translatable)) {
  538. // If there is nothing translatable in this configuration or not
  539. // supported, skip it.
  540. continue;
  541. }
  542. $active_langcode = $this->getActiveConfigLangcode($name);
  543. $active = $this->configStorage->read($name);
  544. foreach ($langcodes as $langcode) {
  545. $processed = $this->processTranslatableData($name, $active, $translatable, $langcode);
  546. // If the language code is not the same as the active storage
  547. // language, we should update the configuration override.
  548. if ($langcode != $active_langcode) {
  549. $override = $this->languageManager->getLanguageConfigOverride($langcode, $name);
  550. // Filter out locale managed configuration keys so that translations
  551. // removed from Locale will be reflected in the config override.
  552. $data = $this->filterOverride($override->get(), $translatable);
  553. if (!empty($processed)) {
  554. // Merge in the Locale managed translations with existing data.
  555. $data = NestedArray::mergeDeepArray([$data, $processed], TRUE);
  556. }
  557. if (empty($data) && !$override->isNew()) {
  558. // The configuration override contains Locale overrides that no
  559. // longer exist.
  560. $this->deleteTranslationOverride($name, $langcode);
  561. $count++;
  562. }
  563. elseif (!empty($data)) {
  564. // Update translation data in configuration override.
  565. $this->saveTranslationOverride($name, $langcode, $data);
  566. $count++;
  567. }
  568. }
  569. elseif (locale_is_translatable($langcode)) {
  570. // If the language code is the active storage language, we should
  571. // update. If it is English, we should only update if English is also
  572. // translatable.
  573. $active = NestedArray::mergeDeepArray([$active, $processed], TRUE);
  574. $this->saveTranslationActive($name, $active);
  575. $count++;
  576. }
  577. }
  578. }
  579. return $count;
  580. }
  581. /**
  582. * Filters override data based on default translatable items.
  583. *
  584. * @param array $override_data
  585. * Configuration override data.
  586. * @param array $translatable
  587. * Translatable data array. @see self::getTranslatableData()
  588. *
  589. * @return array
  590. * Nested array of any items of $override_data which did not have keys in
  591. * $translatable. May be empty if $override_data only had items which were
  592. * also in $translatable.
  593. */
  594. protected function filterOverride(array $override_data, array $translatable) {
  595. $filtered_data = [];
  596. foreach ($override_data as $key => $value) {
  597. if (isset($translatable[$key])) {
  598. // If the translatable default configuration has this key, look further
  599. // for subkeys or ignore this element for scalar values.
  600. if (is_array($value)) {
  601. $value = $this->filterOverride($value, $translatable[$key]);
  602. if (!empty($value)) {
  603. $filtered_data[$key] = $value;
  604. }
  605. }
  606. }
  607. else {
  608. // If this key was not in the translatable default configuration,
  609. // keep it.
  610. $filtered_data[$key] = $value;
  611. }
  612. }
  613. return $filtered_data;
  614. }
  615. }