KeyConfigOverrides.php in Key 8
File
src/KeyConfigOverrides.php
View source
<?php
namespace Drupal\key;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ConfigFactoryOverrideInterface;
use Drupal\Core\Config\StorageInterface;
class KeyConfigOverrides implements ConfigFactoryOverrideInterface {
protected $configFactory;
protected $cacheBackend;
protected $mapping;
protected $inOverride = FALSE;
public function __construct(ConfigFactoryInterface $config_factory = NULL, CacheBackendInterface $cache_backend = NULL) {
$this->configFactory = $config_factory ?: \Drupal::configFactory();
$this->cacheBackend = $cache_backend ?: \Drupal::cache('data');
}
public function loadOverrides($names) {
if ($this->inOverride) {
return [];
}
$this->inOverride = TRUE;
$mapping = $this
->getMapping();
if (!$mapping) {
return [];
}
try {
$storage = \Drupal::entityTypeManager()
->getStorage('key');
} catch (\Exception $e) {
return [];
}
$overrides = [];
foreach ($names as $name) {
if (!array_key_exists($name, $mapping)) {
continue;
}
$override = [];
foreach ($mapping[$name] as $config_item => $key_id) {
$key_value = $storage
->load($key_id)
->getKeyValue();
if (!isset($key_value)) {
continue;
}
$config_item_parents = explode('.', $config_item);
NestedArray::setValue($override, $config_item_parents, $key_value);
}
if ($override) {
$overrides[$name] = $override;
}
}
$this->inOverride = FALSE;
return $overrides;
}
public function getCacheSuffix() {
return 'key_config_override';
}
public function getCacheableMetadata($name) {
return new CacheableMetadata();
}
public function createConfigObject($name, $collection = StorageInterface::DEFAULT_COLLECTION) {
return NULL;
}
protected function getMapping() {
if (!$this->mapping) {
$mapping = [];
$override_ids = $this->configFactory
->listAll('key.config_override.');
$overrides = $this->configFactory
->loadMultiple($override_ids);
foreach ($overrides as $id => $override) {
$override = $override
->get();
$config_id = '';
if (!empty($override['config_prefix'])) {
$config_id .= $override['config_prefix'] . '.';
}
if (isset($override['config_name'])) {
$config_id .= $override['config_name'];
}
$config_item = $override['config_item'];
$key_id = $override['key_id'];
$mapping[$config_id][$config_item] = $key_id;
}
$this->mapping = $mapping;
}
return $this->mapping;
}
}