LocaleConfigManager.php 22.9 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\locale;

5
use Drupal\Component\Utility\NestedArray;
6
use Drupal\Core\Config\ConfigFactoryInterface;
7
use Drupal\Core\Config\ConfigManagerInterface;
8 9
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
10
use Drupal\Core\StringTranslation\TranslatableMarkup;
11 12
use Drupal\Core\TypedData\TraversableTypedDataInterface;
use Drupal\Core\TypedData\TypedDataInterface;
13
use Drupal\language\ConfigurableLanguageManagerInterface;
14 15

/**
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
 * Manages configuration supported in part by interface translation.
 *
 * This manager is responsible to update configuration overrides and active
 * translations when interface translation data changes. This allows Drupal to
 * translate user roles, views, blocks, etc. after Drupal has been installed
 * using the locale module's storage. When translations change in locale,
 * LocaleConfigManager::updateConfigTranslations() is invoked to update the
 * corresponding storage of the translation in the original config object or an
 * override.
 *
 * In turn when translated configuration or configuration language overrides are
 * changed, it is the responsibility of LocaleConfigSubscriber to update locale
 * storage.
 *
 * By design locale module only deals with sources in English.
 *
 * @see \Drupal\locale\LocaleConfigSubscriber
33
 */
34 35 36
class LocaleConfigManager {

  /**
37
   * The storage instance for reading configuration data.
38 39 40 41
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $configStorage;
42 43

  /**
44 45
   * The string storage for reading and writing translations.
   *
46
   * @var \Drupal\locale\StringStorageInterface
47 48 49 50 51 52 53 54 55 56
   */
  protected $localeStorage;

  /**
   * Array with preloaded string translations.
   *
   * @var array
   */
  protected $translations;

57 58 59
  /**
   * The configuration factory.
   *
60
   * @var \Drupal\Core\Config\ConfigFactoryInterface
61 62 63
   */
  protected $configFactory;

64 65 66 67 68 69 70
  /**
   * The language manager.
   *
   * @var \Drupal\language\ConfigurableLanguageManagerInterface
   */
  protected $languageManager;

71 72 73 74 75 76 77
  /**
   * The typed config manager.
   *
   * @var \Drupal\Core\Config\TypedConfigManagerInterface
   */
  protected $typedConfigManager;

78
  /**
79 80 81
   * Whether or not configuration translations are being updated from locale.
   *
   * @see self::isUpdatingFromLocale()
82 83 84
   *
   * @var bool
   */
85
  protected $isUpdatingFromLocale = FALSE;
86

87 88 89 90 91 92 93
  /**
   * The locale default config storage instance.
   *
   * @var \Drupal\locale\LocaleDefaultConfigStorage
   */
  protected $defaultConfigStorage;

94 95 96 97 98
  /**
   * The configuration manager.
   *
   * @var \Drupal\Core\Config\ConfigManagerInterface
   */
99
  protected $configManager;
100

101 102 103
  /**
   * 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 111
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
   *   The typed configuration manager.
112
   * @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager
113
   *   The language manager.
114 115
   * @param \Drupal\locale\LocaleDefaultConfigStorage $default_config_storage
   *   The locale default configuration storage.
116 117
   * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
   *   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 121
    $this->configStorage = $config_storage;
    $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 133 134
   *
   * @param string $name
   *   Configuration object name.
   *
135
   * @return array
136 137
   *   Array of Locale translatable elements of the default configuration in
   *   $name.
138
   */
139 140 141
  public function getTranslatableDefaultConfig($name) {
    if ($this->isSupported($name)) {
      // Create typed configuration wrapper based on install storage data.
142
      $data = $this->defaultConfigStorage->read($name);
143
      $typed_config = $this->typedConfigManager->createFromNameAndData($name, $data);
144 145 146 147
      if ($typed_config instanceof TraversableTypedDataInterface) {
        return $this->getTranslatableData($typed_config);
      }
    }
148
    return [];
149 150 151
  }

  /**
152
   * Gets translatable configuration data for a typed configuration element.
153
   *
154 155
   * @param \Drupal\Core\TypedData\TypedDataInterface $element
   *   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 166 167 168 169 170 171
    if ($element instanceof TraversableTypedDataInterface) {
      foreach ($element as $key => $property) {
        $value = $this->getTranslatableData($property);
        if (!empty($value)) {
          $translatable[$key] = $value;
        }
      }
172
    }
173
    else {
174 175 176
      // Something is only translatable by Locale if there is a string in the
      // first place.
      $value = $element->getValue();
177
      $definition = $element->getDataDefinition();
178
      if (!empty($definition['translatable']) && $value !== '' && $value !== NULL) {
179
        $options = [];
180 181
        if (isset($definition['translation context'])) {
          $options['context'] = $definition['translation context'];
182
        }
183
        return new TranslatableMarkup($value, [], $options);
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
      }
    }
    return $translatable;
  }

  /**
   * Process the translatable data array with a given language.
   *
   * If the given language is translatable, will return the translated copy
   * which will only contain strings that had translations. If the given
   * language is English and is not translatable, will return a simplified
   * array of the English source strings only.
   *
   * @param string $name
   *   The configuration name.
   * @param array $active
   *   The active configuration data.
201
   * @param array|\Drupal\Core\StringTranslation\TranslatableMarkup[] $translatable
202 203
   *   The translatable array structure. A nested array matching the exact
   *   structure under of the default configuration for $name with only the
204
   *   elements that are translatable wrapped into a TranslatableMarkup.
205 206 207 208 209 210 211
   * @param string $langcode
   *   The language code to process the array with.
   *
   * @return array
   *   Processed translatable data array. Will only contain translations
   *   different from source strings or in case of untranslatable English, the
   *   source strings themselves.
212 213
   *
   * @see self::getTranslatableData()
214 215
   */
  protected function processTranslatableData($name, array $active, array $translatable, $langcode) {
216
    $translated = [];
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    foreach ($translatable as $key => $item) {
      if (!isset($active[$key])) {
        continue;
      }
      if (is_array($item)) {
        // Only add this key if there was a translated value underneath.
        $value = $this->processTranslatableData($name, $active[$key], $item, $langcode);
        if (!empty($value)) {
          $translated[$key] = $value;
        }
      }
      else {
        if (locale_is_translatable($langcode)) {
          $value = $this->translateString($name, $langcode, $item->getUntranslatedString(), $item->getOption('context'));
        }
        else {
          $value = $item->getUntranslatedString();
        }
        if (!empty($value)) {
          $translated[$key] = $value;
237 238 239
        }
      }
    }
240
    return $translated;
241 242 243
  }

  /**
244
   * Saves translated configuration override.
245 246 247 248 249 250 251 252
   *
   * @param string $name
   *   Configuration object name.
   * @param string $langcode
   *   Language code.
   * @param array $data
   *   Configuration data to be saved, that will be only the translated values.
   */
253 254
  protected function saveTranslationOverride($name, $langcode, array $data) {
    $this->isUpdatingFromLocale = TRUE;
255
    $this->languageManager->getLanguageConfigOverride($langcode, $name)->setData($data)->save();
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    $this->isUpdatingFromLocale = FALSE;
  }

  /**
   * Saves translated configuration data.
   *
   * @param string $name
   *   Configuration object name.
   * @param array $data
   *   Configuration data to be saved with translations merged in.
   */
  protected function saveTranslationActive($name, array $data) {
    $this->isUpdatingFromLocale = TRUE;
    $this->configFactory->getEditable($name)->setData($data)->save();
    $this->isUpdatingFromLocale = FALSE;
271 272 273 274 275 276 277 278 279 280
  }

  /**
   * Deletes translated configuration data.
   *
   * @param string $name
   *   Configuration object name.
   * @param string $langcode
   *   Language code.
   */
281 282
  protected function deleteTranslationOverride($name, $langcode) {
    $this->isUpdatingFromLocale = TRUE;
283
    $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
284
    $this->isUpdatingFromLocale = FALSE;
285 286 287 288 289 290 291 292 293 294 295 296
  }

  /**
   * Gets configuration names associated with components.
   *
   * @param array $components
   *   (optional) Array of component lists indexed by type. If not present or it
   *   is an empty array, it will update all components.
   *
   * @return array
   *   Array of configuration object names.
   */
297
  public function getComponentNames(array $components = []) {
298 299
    $components = array_filter($components);
    if ($components) {
300
      $names = [];
301 302 303
      foreach ($components as $type => $list) {
        // InstallStorage::getComponentNames returns a list of folders keyed by
        // config name.
304
        $names = array_merge($names, $this->defaultConfigStorage->getComponentNames($type, $list));
305 306 307 308
      }
      return $names;
    }
    else {
309
      return $this->defaultConfigStorage->listAll();
310 311 312 313 314 315 316 317 318 319 320 321 322
    }
  }

  /**
   * Gets configuration names associated with strings.
   *
   * @param array $lids
   *   Array with string identifiers.
   *
   * @return array
   *   Array of configuration object names.
   */
  public function getStringNames(array $lids) {
323 324
    $names = [];
    $locations = $this->localeStorage->getLocations(['sid' => $lids, 'type' => 'configuration']);
325 326 327 328 329 330 331 332 333 334 335 336 337
    foreach ($locations as $location) {
      $names[$location->name] = $location->name;
    }
    return $names;
  }

  /**
   * Deletes configuration for language.
   *
   * @param string $langcode
   *   Language code to delete.
   */
  public function deleteLanguageTranslations($langcode) {
338
    $this->isUpdatingFromLocale = TRUE;
339 340 341
    $storage = $this->languageManager->getLanguageConfigOverrideStorage($langcode);
    foreach ($storage->listAll() as $name) {
      $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
342
    }
343
    $this->isUpdatingFromLocale = FALSE;
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
  }

  /**
   * Translates string using the localization system.
   *
   * So far we only know how to translate strings from English so the source
   * string should be in English.
   * Unlike regular t() translations, strings will be added to the source
   * tables only if this is marked as default data.
   *
   * @param string $name
   *   Name of the configuration location.
   * @param string $langcode
   *   Language code to translate to.
   * @param string $source
   *   The source string, should be English.
   * @param string $context
   *   The string context.
   *
   * @return string|false
   *   Translated string if there is a translation, FALSE if not.
   */
  public function translateString($name, $langcode, $source, $context) {
    if ($source) {
      // If translations for a language have not been loaded yet.
      if (!isset($this->translations[$name][$langcode])) {
        // Preload all translations for this configuration name and language.
371 372
        $this->translations[$name][$langcode] = [];
        foreach ($this->localeStorage->getTranslations(['language' => $langcode, 'type' => 'configuration', 'name' => $name]) as $string) {
373 374 375 376 377 378
          $this->translations[$name][$langcode][$string->context][$string->source] = $string;
        }
      }
      if (!isset($this->translations[$name][$langcode][$context][$source])) {
        // There is no translation of the source string in this config location
        // to this language for this context.
379
        if ($translation = $this->localeStorage->findTranslation(['source' => $source, 'context' => $context, 'language' => $langcode])) {
380 381 382 383 384
          // Look for a translation of the string. It might have one, but not
          // be saved in this configuration location yet.
          // If the string has a translation for this context to this language,
          // save it in the configuration location so it can be looked up faster
          // next time.
385
          $this->localeStorage->createString((array) $translation)
386 387 388 389 390 391 392 393
            ->addLocation('configuration', $name)
            ->save();
        }
        else {
          // No translation was found. Add the source to the configuration
          // location so it can be translated, and the string is faster to look
          // for next time.
          $translation = $this->localeStorage
394
            ->createString(['source' => $source, 'context' => $context])
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
            ->addLocation('configuration', $name)
            ->save();
        }

        // Add an entry, either the translation found, or a blank string object
        // to track the source string, to this configuration location, language,
        // and context.
        $this->translations[$name][$langcode][$context][$source] = $translation;
      }

      // Return the string only when the string object had a translation.
      if ($this->translations[$name][$langcode][$context][$source]->isTranslation()) {
        return $this->translations[$name][$langcode][$context][$source]->getString();
      }
    }
    return FALSE;
  }

413 414 415 416 417 418
  /**
   * Reset static cache of configuration string translations.
   *
   * @return $this
   */
  public function reset() {
419
    $this->translations = [];
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    return $this;
  }

  /**
   * Get the translation object for the given source/context and language.
   *
   * @param string $name
   *   Name of the configuration location.
   * @param string $langcode
   *   Language code to translate to.
   * @param string $source
   *   The source string, should be English.
   * @param string $context
   *   The string context.
   *
435
   * @return \Drupal\locale\TranslationString|false
436 437 438 439 440 441 442
   *   The translation object if the string was not empty or FALSE otherwise.
   */
  public function getStringTranslation($name, $langcode, $source, $context) {
    if ($source) {
      $this->translateString($name, $langcode, $source, $context);
      if ($string = $this->translations[$name][$langcode][$context][$source]) {
        if (!$string->isTranslation()) {
443
          $conditions = ['lid' => $string->lid, 'language' => $langcode];
444 445 446
          $translation = $this->localeStorage->createTranslation($conditions);
          $this->translations[$name][$langcode][$context][$source] = $translation;
          return $translation;
447 448 449 450 451 452 453 454 455
        }
        else {
          return $string;
        }
      }
    }
    return FALSE;
  }

456 457 458 459 460
  /**
   * Checks whether a language has configuration translation.
   *
   * @param string $name
   *   Configuration name.
461 462
   * @param string $langcode
   *   A language code.
463 464 465 466
   *
   * @return bool
   *   A boolean indicating if a language has configuration translations.
   */
467 468
  public function hasTranslation($name, $langcode) {
    $translation = $this->languageManager->getLanguageConfigOverride($langcode, $name);
469
    return !$translation->isNew();
470 471
  }

472
  /**
473 474 475 476 477 478 479 480 481 482 483 484
   * Returns the original language code for this shipped configuration.
   *
   * @param string $name
   *   The configuration name.
   *
   * @return null|string
   *   Language code of the default configuration for $name. If the default
   *   configuration data for $name did not contain a language code, it is
   *   assumed to be English. The return value is NULL if no such default
   *   configuration exists.
   */
  public function getDefaultConfigLangcode($name) {
485 486 487 488 489
    // Config entities that do not have the 'default_config_hash' cannot be
    // shipped configuration regardless of whether there is a name match.
    // configurable_language entities are a special case since they can be
    // translated regardless of whether they are shipped if they in the standard
    // language list.
490
    $config_entity_type = $this->configManager->getEntityTypeIdByName($name);
491 492 493 494 495 496 497
    if (!$config_entity_type || $config_entity_type === 'configurable_language'
      || !empty($this->configFactory->get($name)->get('_core.default_config_hash'))
    ) {
      $shipped = $this->defaultConfigStorage->read($name);
      if (!empty($shipped)) {
        return !empty($shipped['langcode']) ? $shipped['langcode'] : 'en';
      }
498
    }
499
    return NULL;
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
  }

  /**
   * Returns the current language code for this active configuration.
   *
   * @param string $name
   *   The configuration name.
   *
   * @return null|string
   *   Language code of the current active configuration for $name. If the
   *   configuration data for $name did not contain a language code, it is
   *   assumed to be English. The return value is NULL if no such active
   *   configuration exists.
   */
  public function getActiveConfigLangcode($name) {
    $active = $this->configStorage->read($name);
    if (!empty($active)) {
      return !empty($active['langcode']) ? $active['langcode'] : 'en';
    }
  }

  /**
   * Whether the given configuration is supported for interface translation.
   *
   * @param string $name
   *   The configuration name.
   *
   * @return bool
   *   TRUE if interface translation is supported.
   */
  public function isSupported($name) {
    return $this->getDefaultConfigLangcode($name) == 'en' && $this->configStorage->read($name);
  }

  /**
   * Indicates whether configuration translations are being updated from locale.
536 537 538
   *
   * @return bool
   *   Whether or not configuration translations are currently being updated.
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
   *   If TRUE, LocaleConfigManager is in control of the process and the
   *   reference data is locale's storage. Changes made to active configuration
   *   and overrides in this case should not feed back to locale storage.
   *   On the other hand, when not updating from locale and configuration
   *   translations change, we need to feed back to the locale storage.
   */
  public function isUpdatingTranslationsFromLocale() {
    return $this->isUpdatingFromLocale;
  }

  /**
   * Updates all configuration translations for the names / languages provided.
   *
   * To be used when interface translation changes result in the need to update
   * configuration translations to keep them in sync.
   *
   * @param array $names
   *   Array of names of configuration objects to update.
   * @param array $langcodes
   *   (optional) Array of language codes to update. Defaults to all
   *   configurable languages.
   *
   * @return int
   *   Total number of configuration override and active configuration objects
   *   updated (saved or removed).
   */
565
  public function updateConfigTranslations(array $names, array $langcodes = []) {
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
    $langcodes = $langcodes ? $langcodes : array_keys($this->languageManager->getLanguages());
    $count = 0;
    foreach ($names as $name) {
      $translatable = $this->getTranslatableDefaultConfig($name);
      if (empty($translatable)) {
        // If there is nothing translatable in this configuration or not
        // supported, skip it.
        continue;
      }

      $active_langcode = $this->getActiveConfigLangcode($name);
      $active = $this->configStorage->read($name);

      foreach ($langcodes as $langcode) {
        $processed = $this->processTranslatableData($name, $active, $translatable, $langcode);
581 582
        // If the language code is not the same as the active storage
        // language, we should update the configuration override.
583
        if ($langcode != $active_langcode) {
584 585 586 587
          $override = $this->languageManager->getLanguageConfigOverride($langcode, $name);
          // Filter out locale managed configuration keys so that translations
          // removed from Locale will be reflected in the config override.
          $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 593 594 595
          }
          if (empty($data) && !$override->isNew()) {
            // The configuration override contains Locale overrides that no
            // longer exist.
            $this->deleteTranslationOverride($name, $langcode);
596 597
            $count++;
          }
598 599 600 601
          elseif (!empty($data)) {
            // Update translation data in configuration override.
            $this->saveTranslationOverride($name, $langcode, $data);
            $count++;
602 603 604 605 606 607
          }
        }
        elseif (locale_is_translatable($langcode)) {
          // If the language code is the active storage language, we should
          // update. If it is English, we should only update if English is also
          // translatable.
608
          $active = NestedArray::mergeDeepArray([$active, $processed], TRUE);
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
          $this->saveTranslationActive($name, $active);
          $count++;
        }
      }
    }
    return $count;
  }

  /**
   * Filters override data based on default translatable items.
   *
   * @param array $override_data
   *   Configuration override data.
   * @param array $translatable
   *   Translatable data array. @see self::getTranslatableData()
   * @return array
   *   Nested array of any items of $override_data which did not have keys in
   *   $translatable. May be empty if $override_data only had items which were
   *   also in $translatable.
628
   */
629
  protected function filterOverride(array $override_data, array $translatable) {
630
    $filtered_data = [];
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
    foreach ($override_data as $key => $value) {
      if (isset($translatable[$key])) {
        // If the translatable default configuration has this key, look further
        // for subkeys or ignore this element for scalar values.
        if (is_array($value)) {
          $value = $this->filterOverride($value, $translatable[$key]);
          if (!empty($value)) {
            $filtered_data[$key] = $value;
          }
        }
      }
      else {
        // If this key was not in the translatable default configuration,
        // keep it.
        $filtered_data[$key] = $value;
      }
    }
    return $filtered_data;
649 650
  }

651
}