LocaleConfigManager.php 22.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\locale\LocaleConfigManager.
 */

namespace Drupal\locale;

10
use Drupal\Component\Utility\NestedArray;
11
use Drupal\Core\Config\ConfigFactoryInterface;
12
use Drupal\Core\Config\InstallStorage;
13 14 15 16 17
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\StringTranslation\TranslationWrapper;
use Drupal\Core\TypedData\TraversableTypedDataInterface;
use Drupal\Core\TypedData\TypedDataInterface;
18
use Drupal\language\ConfigurableLanguageManagerInterface;
19 20

/**
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
 * 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
38
 */
39 40 41
class LocaleConfigManager {

  /**
42
   * The storage instance for reading configuration data.
43 44 45 46
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $configStorage;
47 48

  /**
49 50 51
   * The string storage for reading and writing translations.
   *
   * @var \Drupal\locale\StringStorageInterface;
52 53 54 55 56 57 58 59 60 61
   */
  protected $localeStorage;

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

62 63 64
  /**
   * The configuration factory.
   *
65
   * @var \Drupal\Core\Config\ConfigFactoryInterface
66 67 68
   */
  protected $configFactory;

69 70 71 72 73 74 75
  /**
   * The language manager.
   *
   * @var \Drupal\language\ConfigurableLanguageManagerInterface
   */
  protected $languageManager;

76 77 78 79 80 81 82
  /**
   * The typed config manager.
   *
   * @var \Drupal\Core\Config\TypedConfigManagerInterface
   */
  protected $typedConfigManager;

83
  /**
84 85 86
   * Whether or not configuration translations are being updated from locale.
   *
   * @see self::isUpdatingFromLocale()
87 88 89
   *
   * @var bool
   */
90
  protected $isUpdatingFromLocale = FALSE;
91

92 93 94 95 96 97 98
  /**
   * The locale default config storage instance.
   *
   * @var \Drupal\locale\LocaleDefaultConfigStorage
   */
  protected $defaultConfigStorage;

99 100 101
  /**
   * Creates a new typed configuration manager.
   *
102
   * @param \Drupal\Core\Config\StorageInterface $config_storage
103
   *   The storage object to use for reading configuration data.
104
   * @param \Drupal\locale\StringStorageInterface $locale_storage
105
   *   The locale storage to use for reading string translations.
106
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
107
   *   The configuration factory
108 109
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
   *   The typed configuration manager.
110
   * @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager
111
   *   The language manager.
112 113
   * @param \Drupal\locale\LocaleDefaultConfigStorage $default_config_storage
   *   The locale default configuration storage.
114
   */
115
  public function __construct(StorageInterface $config_storage, StringStorageInterface $locale_storage, ConfigFactoryInterface $config_factory, TypedConfigManagerInterface $typed_config, ConfigurableLanguageManagerInterface $language_manager, LocaleDefaultConfigStorage $default_config_storage) {
116 117
    $this->configStorage = $config_storage;
    $this->localeStorage = $locale_storage;
118
    $this->configFactory = $config_factory;
119
    $this->typedConfigManager = $typed_config;
120
    $this->languageManager = $language_manager;
121
    $this->defaultConfigStorage = $default_config_storage;
122 123 124
  }

  /**
125
   * Gets array of translation wrappers for translatable configuration.
126 127 128 129
   *
   * @param string $name
   *   Configuration object name.
   *
130 131
   * @return array
   *   Array of translatable elements of the default configuration in $name.
132
   */
133 134 135
  public function getTranslatableDefaultConfig($name) {
    if ($this->isSupported($name)) {
      // Create typed configuration wrapper based on install storage data.
136
      $data = $this->defaultConfigStorage->read($name);
137
      $type_definition = $this->typedConfigManager->getDefinition($name);
138 139 140 141 142 143 144
      $data_definition = $this->typedConfigManager->buildDataDefinition($type_definition, $data);
      $typed_config = $this->typedConfigManager->create($data_definition, $data);
      if ($typed_config instanceof TraversableTypedDataInterface) {
        return $this->getTranslatableData($typed_config);
      }
    }
    return array();
145 146 147
  }

  /**
148
   * Gets translatable configuration data for a typed configuration element.
149
   *
150 151
   * @param \Drupal\Core\TypedData\TypedDataInterface $element
   *   Typed configuration element.
152
   *
153 154 155 156 157
   * @return array|\Drupal\Core\StringTranslation\TranslationWrapper
   *   A nested array matching the exact structure under $element with only the
   *   elements that are translatable wrapped into a TranslationWrapper. If the
   *   provided $element is not traversable, the return value is a single
   *   TranslationWrapper.
158
   */
159 160 161 162 163 164 165 166 167
  protected function getTranslatableData(TypedDataInterface $element) {
    $translatable = array();
    if ($element instanceof TraversableTypedDataInterface) {
      foreach ($element as $key => $property) {
        $value = $this->getTranslatableData($property);
        if (!empty($value)) {
          $translatable[$key] = $value;
        }
      }
168
    }
169 170 171 172 173 174
    else {
      $definition = $element->getDataDefinition();
      if (!empty($definition['translatable'])) {
        $options = array();
        if (isset($definition['translation context'])) {
          $options['context'] = $definition['translation context'];
175
        }
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
        return new TranslationWrapper($element->getValue(), array(), $options);
      }
    }
    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.
   * @param array|\Drupal\Core\StringTranslation\TranslationWrapper[] $translatable
   *   The translatable array structure. A nested array matching the exact
   *   structure under of the default configuration for $name with only the
   *   elements that are translatable wrapped into a TranslationWrapper.
   *   @see self::getTranslatableData().
   * @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.
   */
  protected function processTranslatableData($name, array $active, array $translatable, $langcode) {
    $translated = array();
    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;
229 230 231
        }
      }
    }
232
    return $translated;
233 234 235
  }

  /**
236
   * Saves translated configuration override.
237 238 239 240 241 242 243 244
   *
   * @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.
   */
245 246
  protected function saveTranslationOverride($name, $langcode, array $data) {
    $this->isUpdatingFromLocale = TRUE;
247
    $this->languageManager->getLanguageConfigOverride($langcode, $name)->setData($data)->save();
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    $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;
263 264 265 266 267 268 269 270 271 272
  }

  /**
   * Deletes translated configuration data.
   *
   * @param string $name
   *   Configuration object name.
   * @param string $langcode
   *   Language code.
   */
273 274
  protected function deleteTranslationOverride($name, $langcode) {
    $this->isUpdatingFromLocale = TRUE;
275
    $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
276
    $this->isUpdatingFromLocale = FALSE;
277 278 279 280 281 282 283 284 285 286 287 288
  }

  /**
   * 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.
   */
289
  public function getComponentNames(array $components = array()) {
290 291 292 293 294 295
    $components = array_filter($components);
    if ($components) {
      $names = array();
      foreach ($components as $type => $list) {
        // InstallStorage::getComponentNames returns a list of folders keyed by
        // config name.
296
        $names = array_merge($names, $this->defaultConfigStorage->getComponentNames($type, $list));
297 298 299 300
      }
      return $names;
    }
    else {
301
      return $this->defaultConfigStorage->listAll();
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    }
  }

  /**
   * 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) {
    $names = array();
    $locations = $this->localeStorage->getLocations(array('sid' => $lids, 'type' => 'configuration'));
    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) {
330
    $this->isUpdatingFromLocale = TRUE;
331 332 333
    $storage = $this->languageManager->getLanguageConfigOverrideStorage($langcode);
    foreach ($storage->listAll() as $name) {
      $this->languageManager->getLanguageConfigOverride($langcode, $name)->delete();
334
    }
335
    $this->isUpdatingFromLocale = FALSE;
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
  }

  /**
   * 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.
        $this->translations[$name][$langcode] = array();
364
        foreach ($this->localeStorage->getTranslations(array('language' => $langcode, 'type' => 'configuration', 'name' => $name)) as $string) {
365 366 367 368 369 370 371 372 373 374 375 376
          $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.
        if ($translation = $this->localeStorage->findTranslation(array('source' => $source, 'context' => $context, 'language' => $langcode))) {
          // 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.
377
          $this->localeStorage->createString((array) $translation)
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
            ->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
            ->createString(array('source' => $source, 'context' => $context))
            ->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;
  }

405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
  /**
   * Reset static cache of configuration string translations.
   *
   * @return $this
   */
  public function reset() {
    $this->translations = array();
    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.
   *
   * @return \Drupal\locale\TranslationString|FALSE
   *   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()) {
          $conditions = array('lid' => $string->lid, 'language' => $langcode);
436 437 438
          $translation = $this->localeStorage->createTranslation($conditions);
          $this->translations[$name][$langcode][$context][$source] = $translation;
          return $translation;
439 440 441 442 443 444 445 446 447
        }
        else {
          return $string;
        }
      }
    }
    return FALSE;
  }

448 449 450 451 452
  /**
   * Checks whether a language has configuration translation.
   *
   * @param string $name
   *   Configuration name.
453 454
   * @param string $langcode
   *   A language code.
455 456 457 458
   *
   * @return bool
   *   A boolean indicating if a language has configuration translations.
   */
459 460
  public function hasTranslation($name, $langcode) {
    $translation = $this->languageManager->getLanguageConfigOverride($langcode, $name);
461
    return !$translation->isNew();
462 463
  }

464
  /**
465 466 467 468 469 470 471 472 473 474 475 476
   * 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) {
477
    $shipped = $this->defaultConfigStorage->read($name);
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    if (!empty($shipped)) {
      return !empty($shipped['langcode']) ? $shipped['langcode'] : 'en';
    }
  }

  /**
   * 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.
517 518 519
   *
   * @return bool
   *   Whether or not configuration translations are currently being updated.
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 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 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
   *   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).
   */
  public function updateConfigTranslations(array $names, array $langcodes = array()) {
    $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);
        if ($langcode != $active_langcode) {
          // If the language code is not the same as the active storage
          // language, we should update a configuration override.
          if (!empty($processed)) {
            // Update translation data in configuration override.
            $this->saveTranslationOverride($name, $langcode, $processed);
            $count++;
          }
          else {
            $override = $this->languageManager->getLanguageConfigOverride($langcode, $name);
            if (!$override->isNew()) {
              $data = $this->filterOverride($override->get(), $translatable);
              if (empty($data)) {
                // Delete language override if there is no data left at all.
                // This means all prior translations in the override were locale
                // managed.
                $this->deleteTranslationOverride($name, $langcode);
                $count++;
              }
              else {
                // If there were translatable elements besides locale managed
                // items, save with only those, and remove the ones managed
                // by locale only.
                $this->saveTranslationOverride($name, $langcode, $data);
                $count++;
              }
            }
          }
        }
        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.
          $active = NestedArray::mergeDeepArray(array($active, $processed), TRUE);
          $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.
615
   */
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
  protected function filterOverride(array $override_data, array $translatable) {
    $filtered_data = array();
    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;
636 637
  }

638
}