3 namespace Drupal\Core\Config\Entity;
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Config\ConfigFactoryInterface;
7 use Drupal\Core\Config\ConfigImporterException;
8 use Drupal\Core\Entity\EntityInterface;
9 use Drupal\Core\Entity\EntityMalformedException;
10 use Drupal\Core\Entity\EntityStorageBase;
11 use Drupal\Core\Config\Config;
12 use Drupal\Core\Config\Entity\Exception\ConfigEntityIdLengthException;
13 use Drupal\Core\Entity\EntityTypeInterface;
14 use Drupal\Component\Uuid\UuidInterface;
15 use Drupal\Core\Language\LanguageManagerInterface;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
19 * Defines the storage class for configuration entities.
21 * Configuration object names of configuration entities are comprised of two
22 * parts, separated by a dot:
23 * - config_prefix: A string denoting the owner (module/extension) of the
24 * configuration object, followed by arbitrary other namespace identifiers
25 * that are declared by the owning extension; e.g., 'node.type'. The
26 * config_prefix does NOT contain a trailing dot. It is defined by the entity
28 * - ID: A string denoting the entity ID within the entity type namespace; e.g.,
29 * 'article'. Entity IDs may contain dots/periods. The entire remaining string
30 * after the config_prefix in a config name forms the entity ID. Additional or
31 * custom suffixes are not possible.
35 class ConfigEntityStorage extends EntityStorageBase implements ConfigEntityStorageInterface, ImportableEntityStorageInterface {
38 * Length limit of the configuration entity ID.
40 * Most file systems limit a file name's length to 255 characters, so
41 * ConfigBase::MAX_NAME_LENGTH restricts the full configuration object name
42 * to 250 characters (leaving 5 for the file extension). The config prefix
43 * is limited by ConfigEntityType::PREFIX_LENGTH to 83 characters, so this
44 * leaves 166 remaining characters for the configuration entity ID, with 1
45 * additional character needed for the joining dot.
47 * @see \Drupal\Core\Config\ConfigBase::MAX_NAME_LENGTH
48 * @see \Drupal\Core\Config\Entity\ConfigEntityType::PREFIX_LENGTH
50 const MAX_ID_LENGTH = 166;
55 protected $uuidKey = 'uuid';
58 * The config factory service.
60 * @var \Drupal\Core\Config\ConfigFactoryInterface
62 protected $configFactory;
65 * The config storage service.
67 * @var \Drupal\Core\Config\StorageInterface
69 protected $configStorage;
72 * The language manager.
74 * @var \Drupal\Core\Language\LanguageManagerInterface
76 protected $languageManager;
79 * Static cache of entities, keyed first by entity ID, then by an extra key.
81 * The additional cache key is to maintain separate caches for different
82 * states of config overrides.
85 * @see \Drupal\Core\Config\ConfigFactoryInterface::getCacheKeys().
87 protected $entities = [];
90 * Determines if the underlying configuration is retrieved override free.
94 protected $overrideFree = FALSE;
97 * Constructs a ConfigEntityStorage object.
99 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
100 * The entity type definition.
101 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
102 * The config factory service.
103 * @param \Drupal\Component\Uuid\UuidInterface $uuid_service
105 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
106 * The language manager.
108 public function __construct(EntityTypeInterface $entity_type, ConfigFactoryInterface $config_factory, UuidInterface $uuid_service, LanguageManagerInterface $language_manager) {
109 parent::__construct($entity_type);
111 $this->configFactory = $config_factory;
112 $this->uuidService = $uuid_service;
113 $this->languageManager = $language_manager;
119 public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
122 $container->get('config.factory'),
123 $container->get('uuid'),
124 $container->get('language_manager')
131 public function loadRevision($revision_id) {
138 public function deleteRevision($revision_id) {
143 * Returns the prefix used to create the configuration name.
145 * The prefix consists of the config prefix from the entity type plus a dot
146 * for separating from the ID.
149 * The full configuration prefix, for example 'views.view.'.
151 protected function getPrefix() {
152 return $this->entityType->getConfigPrefix() . '.';
158 public static function getIDFromConfigName($config_name, $config_prefix) {
159 return substr($config_name, strlen($config_prefix . '.'));
165 protected function doLoadMultiple(array $ids = NULL) {
166 $prefix = $this->getPrefix();
168 // Get the names of the configuration entities we are going to load.
170 $names = $this->configFactory->listAll($prefix);
174 foreach ($ids as $id) {
175 // Add the prefix to the ID to serve as the configuration object name.
176 $names[] = $prefix . $id;
180 // Load all of the configuration entities.
181 /** @var \Drupal\Core\Config\Config[] $configs */
184 foreach ($this->configFactory->loadMultiple($names) as $config) {
185 $id = $config->get($this->idKey);
186 $records[$id] = $this->overrideFree ? $config->getOriginal(NULL, FALSE) : $config->get();
187 $configs[$id] = $config;
189 $entities = $this->mapFromStorageRecords($records, $configs);
191 // Config entities wrap config objects, and therefore they need to inherit
192 // the cacheability metadata of config objects (to ensure e.g. additional
193 // cacheability metadata added by config overrides is not lost).
194 foreach ($entities as $id => $entity) {
195 // But rather than simply inheriting all cacheability metadata of config
196 // objects, we need to make sure the self-referring cache tag that is
197 // present on Config objects is not added to the Config entity. It must be
198 // removed for 3 reasons:
199 // 1. When renaming/duplicating a Config entity, the cache tag of the
200 // original config object would remain present, which would be wrong.
201 // 2. Some Config entities choose to not use the cache tag that the under-
202 // lying Config object provides by default (For performance and
203 // cacheability reasons it may not make sense to have a unique cache
204 // tag for every Config entity. The DateFormat Config entity specifies
205 // the 'rendered' cache tag for example, because A) date formats are
206 // changed extremely rarely, so invalidating all render cache items is
207 // fine, B) it means fewer cache tags per page.).
208 // 3. Fewer cache tags is better for performance.
209 $self_referring_cache_tag = ['config:' . $configs[$id]->getName()];
210 $config_cacheability = CacheableMetadata::createFromObject($configs[$id]);
211 $config_cacheability->setCacheTags(array_diff($config_cacheability->getCacheTags(), $self_referring_cache_tag));
212 $entity->addCacheableDependency($config_cacheability);
221 protected function doCreate(array $values) {
222 // Set default language to current language if not provided.
223 $values += [$this->langcodeKey => $this->languageManager->getCurrentLanguage()->getId()];
224 $entity = new $this->entityClass($values, $this->entityTypeId);
232 protected function doDelete($entities) {
233 foreach ($entities as $entity) {
234 $this->configFactory->getEditable($this->getPrefix() . $entity->id())->delete();
239 * Implements Drupal\Core\Entity\EntityStorageInterface::save().
241 * @throws EntityMalformedException
242 * When attempting to save a configuration entity that has no ID.
244 public function save(EntityInterface $entity) {
245 // Configuration entity IDs are strings, and '0' is a valid ID.
247 if ($id === NULL || $id === '') {
248 throw new EntityMalformedException('The entity does not have an ID.');
251 // Check the configuration entity ID length.
252 // @see \Drupal\Core\Config\Entity\ConfigEntityStorage::MAX_ID_LENGTH
253 // @todo Consider moving this to a protected method on the parent class, and
254 // abstracting it for all entity types.
255 if (strlen($entity->get($this->idKey)) > self::MAX_ID_LENGTH) {
256 throw new ConfigEntityIdLengthException("Configuration entity ID {$entity->get($this->idKey)} exceeds maximum allowed length of " . self::MAX_ID_LENGTH . " characters.");
259 return parent::save($entity);
265 protected function doSave($id, EntityInterface $entity) {
266 $is_new = $entity->isNew();
267 $prefix = $this->getPrefix();
268 $config_name = $prefix . $entity->id();
269 if ($id !== $entity->id()) {
270 // Renaming a config object needs to cater for:
271 // - Storage needs to access the original object.
272 // - The object needs to be renamed/copied in ConfigFactory and reloaded.
273 // - All instances of the object need to be renamed.
274 $this->configFactory->rename($prefix . $id, $config_name);
276 $config = $this->configFactory->getEditable($config_name);
278 // Retrieve the desired properties and set them in config.
279 $config->setData($this->mapToStorageRecord($entity));
280 $config->save($entity->hasTrustedData());
282 // Update the entity with the values stored in configuration. It is possible
283 // that configuration schema has casted some of the values.
284 if (!$entity->hasTrustedData()) {
285 $data = $this->mapFromStorageRecords([$config->get()]);
286 $updated_entity = current($data);
288 foreach (array_keys($config->get()) as $property) {
289 $value = $updated_entity->get($property);
290 $entity->set($property, $value);
294 return $is_new ? SAVED_NEW : SAVED_UPDATED;
298 * Maps from an entity object to the storage record.
300 * @param \Drupal\Core\Entity\EntityInterface $entity
304 * The record to store.
306 protected function mapToStorageRecord(EntityInterface $entity) {
307 return $entity->toArray();
313 protected function has($id, EntityInterface $entity) {
314 $prefix = $this->getPrefix();
315 $config = $this->configFactory->get($prefix . $id);
316 return !$config->isNew();
320 * Gets entities from the static cache.
323 * If not empty, return entities that match these IDs.
325 * @return \Drupal\Core\Entity\EntityInterface[]
326 * Array of entities from the entity cache.
328 protected function getFromStaticCache(array $ids) {
330 // Load any available entities from the internal cache.
331 if ($this->entityType->isStaticallyCacheable() && !empty($this->entities)) {
332 $config_overrides_key = $this->overrideFree ? '' : implode(':', $this->configFactory->getCacheKeys());
333 foreach ($ids as $id) {
334 if (!empty($this->entities[$id])) {
335 if (isset($this->entities[$id][$config_overrides_key])) {
336 $entities[$id] = $this->entities[$id][$config_overrides_key];
345 * Stores entities in the static entity cache.
347 * @param \Drupal\Core\Entity\EntityInterface[] $entities
348 * Entities to store in the cache.
350 protected function setStaticCache(array $entities) {
351 if ($this->entityType->isStaticallyCacheable()) {
352 $config_overrides_key = $this->overrideFree ? '' : implode(':', $this->configFactory->getCacheKeys());
353 foreach ($entities as $id => $entity) {
354 $this->entities[$id][$config_overrides_key] = $entity;
360 * Invokes a hook on behalf of the entity.
363 * One of 'presave', 'insert', 'update', 'predelete', or 'delete'.
367 protected function invokeHook($hook, EntityInterface $entity) {
369 $this->moduleHandler->invokeAll($this->entityTypeId . '_' . $hook, [$entity]);
370 // Invoke the respective entity-level hook.
371 $this->moduleHandler->invokeAll('entity_' . $hook, [$entity, $this->entityTypeId]);
377 protected function getQueryServiceName() {
378 return 'entity.query.config';
384 public function importCreate($name, Config $new_config, Config $old_config) {
385 $entity = $this->_doCreateFromStorageRecord($new_config->get(), TRUE);
393 public function importUpdate($name, Config $new_config, Config $old_config) {
394 $id = static::getIDFromConfigName($name, $this->entityType->getConfigPrefix());
395 $entity = $this->load($id);
397 throw new ConfigImporterException("Attempt to update non-existing entity '$id'.");
399 $entity->setSyncing(TRUE);
400 $entity = $this->updateFromStorageRecord($entity, $new_config->get());
408 public function importDelete($name, Config $new_config, Config $old_config) {
409 $id = static::getIDFromConfigName($name, $this->entityType->getConfigPrefix());
410 $entity = $this->load($id);
411 $entity->setSyncing(TRUE);
419 public function importRename($old_name, Config $new_config, Config $old_config) {
420 return $this->importUpdate($old_name, $new_config, $old_config);
426 public function createFromStorageRecord(array $values) {
427 return $this->_doCreateFromStorageRecord($values);
431 * Helps create a configuration entity from storage values.
433 * Allows the configuration entity storage to massage storage values before
434 * creating an entity.
436 * @param array $values
437 * The array of values from the configuration storage.
438 * @param bool $is_syncing
439 * Is the configuration entity being created as part of a config sync.
441 * @return ConfigEntityInterface
442 * The configuration entity.
444 * @see \Drupal\Core\Config\Entity\ConfigEntityStorageInterface::createFromStorageRecord()
445 * @see \Drupal\Core\Config\Entity\ImportableEntityStorageInterface::importCreate()
447 protected function _doCreateFromStorageRecord(array $values, $is_syncing = FALSE) {
448 // Assign a new UUID if there is none yet.
449 if ($this->uuidKey && $this->uuidService && !isset($values[$this->uuidKey])) {
450 $values[$this->uuidKey] = $this->uuidService->generate();
452 $data = $this->mapFromStorageRecords([$values]);
453 $entity = current($data);
454 $entity->original = clone $entity;
455 $entity->setSyncing($is_syncing);
456 $entity->enforceIsNew();
457 $entity->postCreate($this);
459 // Modules might need to add or change the data initially held by the new
460 // entity object, for instance to fill-in default values.
461 $this->invokeHook('create', $entity);
469 public function updateFromStorageRecord(ConfigEntityInterface $entity, array $values) {
470 $entity->original = clone $entity;
472 $data = $this->mapFromStorageRecords([$values]);
473 $updated_entity = current($data);
475 foreach (array_keys($values) as $property) {
476 $value = $updated_entity->get($property);
477 $entity->set($property, $value);
486 public function loadOverrideFree($id) {
487 $entities = $this->loadMultipleOverrideFree([$id]);
488 return isset($entities[$id]) ? $entities[$id] : NULL;
494 public function loadMultipleOverrideFree(array $ids = NULL) {
495 $this->overrideFree = TRUE;
496 $entities = $this->loadMultiple($ids);
497 $this->overrideFree = FALSE;