LanguageHierarchyConfigFactoryOverride.php in Language Hierarchy 8
File
src/Config/LanguageHierarchyConfigFactoryOverride.php
View source
<?php
namespace Drupal\language_hierarchy\Config;
use Drupal\Core\Language\LanguageInterface;
use Drupal\language\Config\LanguageConfigFactoryOverride;
class LanguageHierarchyConfigFactoryOverride extends LanguageConfigFactoryOverride {
protected $fallbackChain;
public function loadOverrides($names) {
if ($this->language && (!isset($this->fallbackChain) || !empty($this->fallbackChain))) {
$storage = $this
->getStorage($this->language
->getId());
$loaded = $storage
->readMultiple($names);
if ($missing = array_diff($names, array_keys($loaded))) {
if (!isset($this->fallbackChain)) {
$this->fallbackChain = $this
->getFallbackChainFromBaseConfig($this->language
->getId());
}
$ancestors = $this->fallbackChain;
while ($missing && ($ancestor = array_shift($ancestors))) {
$fallback_storage = $this
->getStorage($ancestor);
$loaded += $fallback_storage
->readMultiple($missing);
$missing = array_diff($names, array_keys($loaded));
}
}
return $loaded;
}
else {
return parent::loadOverrides($names);
}
}
public function getOverride($langcode, $name) {
$source_storage = $target_storage = $this
->getStorage($langcode);
$data = $source_storage
->read($name);
if (empty($data)) {
if ($ancestors = $this
->getFallbackChainFromConfigEntities($langcode)) {
while (empty($data) && ($ancestor = array_shift($ancestors))) {
$fallback_storage = $this
->getStorage($ancestor);
if ($data = $fallback_storage
->read($name)) {
$source_storage = $fallback_storage;
}
}
$override = new LanguageHierarchyConfigOverride($name, $langcode, $source_storage, $target_storage, $this->typedConfigManager, $this->eventDispatcher);
if (!empty($data)) {
$override
->initWithData($data);
}
return $override;
}
}
return parent::getOverride($langcode, $name);
}
public function setLanguage(LanguageInterface $language = NULL) {
$this->fallbackChain = $this
->getFallbackChainFromConfigEntities($language
->getId());
return parent::setLanguage($language);
}
protected function getFallbackChainFromBaseConfig($langcode) {
$language_config = $this->baseStorage
->read('language.entity.' . $langcode);
$fallbacks = [];
while (!empty($language_config['third_party_settings']['language_hierarchy']['fallback_langcode'])) {
$ancestor_langcode = $language_config['third_party_settings']['language_hierarchy']['fallback_langcode'];
if (in_array($ancestor_langcode, $fallbacks, TRUE)) {
break;
}
else {
$fallbacks[] = $ancestor_langcode;
$language_config = $this->baseStorage
->read('language.entity.' . $ancestor_langcode);
}
}
return $fallbacks;
}
protected function getFallbackChainFromConfigEntities($langcode) {
$language_config = \Drupal::entityTypeManager()
->getStorage('configurable_language')
->load($langcode);
$fallbacks = language_hierarchy_get_ancestors($language_config);
return array_keys($fallbacks);
}
}