11b66fc7a1939b23aa1ee7fb08ef5d2b47e2496f
[yaffs-website] / web / core / lib / Drupal / Core / Config / Entity / ConfigEntityStorage.php
1 <?php
2
3 namespace Drupal\Core\Config\Entity;
4
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;
17
18 /**
19  * Defines the storage class for configuration entities.
20  *
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
27  *   type's annotation.
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.
32  *
33  * @ingroup entity_api
34  */
35 class ConfigEntityStorage extends EntityStorageBase implements ConfigEntityStorageInterface, ImportableEntityStorageInterface {
36
37   /**
38    * Length limit of the configuration entity ID.
39    *
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.
46    *
47    * @see \Drupal\Core\Config\ConfigBase::MAX_NAME_LENGTH
48    * @see \Drupal\Core\Config\Entity\ConfigEntityType::PREFIX_LENGTH
49    */
50   const MAX_ID_LENGTH = 166;
51
52   /**
53    * {@inheritdoc}
54    */
55   protected $uuidKey = 'uuid';
56
57   /**
58    * The config factory service.
59    *
60    * @var \Drupal\Core\Config\ConfigFactoryInterface
61    */
62   protected $configFactory;
63
64   /**
65    * The config storage service.
66    *
67    * @var \Drupal\Core\Config\StorageInterface
68    */
69   protected $configStorage;
70
71   /**
72    * The language manager.
73    *
74    * @var \Drupal\Core\Language\LanguageManagerInterface
75    */
76   protected $languageManager;
77
78   /**
79    * Static cache of entities, keyed first by entity ID, then by an extra key.
80    *
81    * The additional cache key is to maintain separate caches for different
82    * states of config overrides.
83    *
84    * @var array
85    * @see \Drupal\Core\Config\ConfigFactoryInterface::getCacheKeys().
86    */
87   protected $entities = [];
88
89   /**
90    * Determines if the underlying configuration is retrieved override free.
91    *
92    * @var bool
93    */
94   protected $overrideFree = FALSE;
95
96   /**
97    * Constructs a ConfigEntityStorage object.
98    *
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
104    *   The UUID service.
105    * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
106    *   The language manager.
107    */
108   public function __construct(EntityTypeInterface $entity_type, ConfigFactoryInterface $config_factory, UuidInterface $uuid_service, LanguageManagerInterface $language_manager) {
109     parent::__construct($entity_type);
110
111     $this->configFactory = $config_factory;
112     $this->uuidService = $uuid_service;
113     $this->languageManager = $language_manager;
114   }
115
116   /**
117    * {@inheritdoc}
118    */
119   public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
120     return new static(
121       $entity_type,
122       $container->get('config.factory'),
123       $container->get('uuid'),
124       $container->get('language_manager')
125     );
126   }
127
128   /**
129    * {@inheritdoc}
130    */
131   public function loadRevision($revision_id) {
132     return NULL;
133   }
134
135   /**
136    * {@inheritdoc}
137    */
138   public function deleteRevision($revision_id) {
139     return NULL;
140   }
141
142   /**
143    * Returns the prefix used to create the configuration name.
144    *
145    * The prefix consists of the config prefix from the entity type plus a dot
146    * for separating from the ID.
147    *
148    * @return string
149    *   The full configuration prefix, for example 'views.view.'.
150    */
151   protected function getPrefix() {
152     return $this->entityType->getConfigPrefix() . '.';
153   }
154
155   /**
156    * {@inheritdoc}
157    */
158   public static function getIDFromConfigName($config_name, $config_prefix) {
159     return substr($config_name, strlen($config_prefix . '.'));
160   }
161
162   /**
163    * {@inheritdoc}
164    */
165   protected function doLoadMultiple(array $ids = NULL) {
166     $prefix = $this->getPrefix();
167
168     // Get the names of the configuration entities we are going to load.
169     if ($ids === NULL) {
170       $names = $this->configFactory->listAll($prefix);
171     }
172     else {
173       $names = [];
174       foreach ($ids as $id) {
175         // Add the prefix to the ID to serve as the configuration object name.
176         $names[] = $prefix . $id;
177       }
178     }
179
180     // Load all of the configuration entities.
181     /** @var \Drupal\Core\Config\Config[] $configs */
182     $configs = [];
183     $records = [];
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;
188     }
189     $entities = $this->mapFromStorageRecords($records, $configs);
190
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);
213     }
214
215     return $entities;
216   }
217
218   /**
219    * {@inheritdoc}
220    */
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);
225
226     return $entity;
227   }
228
229   /**
230    * {@inheritdoc}
231    */
232   protected function doDelete($entities) {
233     foreach ($entities as $entity) {
234       $this->configFactory->getEditable($this->getPrefix() . $entity->id())->delete();
235     }
236   }
237
238   /**
239    * Implements Drupal\Core\Entity\EntityStorageInterface::save().
240    *
241    * @throws EntityMalformedException
242    *   When attempting to save a configuration entity that has no ID.
243    */
244   public function save(EntityInterface $entity) {
245     // Configuration entity IDs are strings, and '0' is a valid ID.
246     $id = $entity->id();
247     if ($id === NULL || $id === '') {
248       throw new EntityMalformedException('The entity does not have an ID.');
249     }
250
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.");
257     }
258
259     return parent::save($entity);
260   }
261
262   /**
263    * {@inheritdoc}
264    */
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);
275     }
276     $config = $this->configFactory->getEditable($config_name);
277
278     // Retrieve the desired properties and set them in config.
279     $config->setData($this->mapToStorageRecord($entity));
280     $config->save($entity->hasTrustedData());
281
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);
287
288       foreach (array_keys($config->get()) as $property) {
289         $value = $updated_entity->get($property);
290         $entity->set($property, $value);
291       }
292     }
293
294     return $is_new ? SAVED_NEW : SAVED_UPDATED;
295   }
296
297   /**
298    * Maps from an entity object to the storage record.
299    *
300    * @param \Drupal\Core\Entity\EntityInterface $entity
301    *   The entity object.
302    *
303    * @return array
304    *   The record to store.
305    */
306   protected function mapToStorageRecord(EntityInterface $entity) {
307     return $entity->toArray();
308   }
309
310   /**
311    * {@inheritdoc}
312    */
313   protected function has($id, EntityInterface $entity) {
314     $prefix = $this->getPrefix();
315     $config = $this->configFactory->get($prefix . $id);
316     return !$config->isNew();
317   }
318
319   /**
320    * Gets entities from the static cache.
321    *
322    * @param array $ids
323    *   If not empty, return entities that match these IDs.
324    *
325    * @return \Drupal\Core\Entity\EntityInterface[]
326    *   Array of entities from the entity cache.
327    */
328   protected function getFromStaticCache(array $ids) {
329     $entities = [];
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];
337           }
338         }
339       }
340     }
341     return $entities;
342   }
343
344   /**
345    * Stores entities in the static entity cache.
346    *
347    * @param \Drupal\Core\Entity\EntityInterface[] $entities
348    *   Entities to store in the cache.
349    */
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;
355       }
356     }
357   }
358
359   /**
360    * Invokes a hook on behalf of the entity.
361    *
362    * @param $hook
363    *   One of 'presave', 'insert', 'update', 'predelete', or 'delete'.
364    * @param $entity
365    *   The entity object.
366    */
367   protected function invokeHook($hook, EntityInterface $entity) {
368     // Invoke the hook.
369     $this->moduleHandler->invokeAll($this->entityTypeId . '_' . $hook, [$entity]);
370     // Invoke the respective entity-level hook.
371     $this->moduleHandler->invokeAll('entity_' . $hook, [$entity, $this->entityTypeId]);
372   }
373
374   /**
375    * {@inheritdoc}
376    */
377   protected function getQueryServiceName() {
378     return 'entity.query.config';
379   }
380
381   /**
382    * {@inheritdoc}
383    */
384   public function importCreate($name, Config $new_config, Config $old_config) {
385     $entity = $this->_doCreateFromStorageRecord($new_config->get(), TRUE);
386     $entity->save();
387     return TRUE;
388   }
389
390   /**
391    * {@inheritdoc}
392    */
393   public function importUpdate($name, Config $new_config, Config $old_config) {
394     $id = static::getIDFromConfigName($name, $this->entityType->getConfigPrefix());
395     $entity = $this->load($id);
396     if (!$entity) {
397       throw new ConfigImporterException("Attempt to update non-existing entity '$id'.");
398     }
399     $entity->setSyncing(TRUE);
400     $entity = $this->updateFromStorageRecord($entity, $new_config->get());
401     $entity->save();
402     return TRUE;
403   }
404
405   /**
406    * {@inheritdoc}
407    */
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);
412     $entity->delete();
413     return TRUE;
414   }
415
416   /**
417    * {@inheritdoc}
418    */
419   public function importRename($old_name, Config $new_config, Config $old_config) {
420     return $this->importUpdate($old_name, $new_config, $old_config);
421   }
422
423   /**
424    * {@inheritdoc}
425    */
426   public function createFromStorageRecord(array $values) {
427     return $this->_doCreateFromStorageRecord($values);
428   }
429
430   /**
431    * Helps create a configuration entity from storage values.
432    *
433    * Allows the configuration entity storage to massage storage values before
434    * creating an entity.
435    *
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.
440    *
441    * @return ConfigEntityInterface
442    *   The configuration entity.
443    *
444    * @see \Drupal\Core\Config\Entity\ConfigEntityStorageInterface::createFromStorageRecord()
445    * @see \Drupal\Core\Config\Entity\ImportableEntityStorageInterface::importCreate()
446    */
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();
451     }
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);
458
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);
462     return $entity;
463
464   }
465
466   /**
467    * {@inheritdoc}
468    */
469   public function updateFromStorageRecord(ConfigEntityInterface $entity, array $values) {
470     $entity->original = clone $entity;
471
472     $data = $this->mapFromStorageRecords([$values]);
473     $updated_entity = current($data);
474
475     foreach (array_keys($values) as $property) {
476       $value = $updated_entity->get($property);
477       $entity->set($property, $value);
478     }
479
480     return $entity;
481   }
482
483   /**
484    * {@inheritdoc}
485    */
486   public function loadOverrideFree($id) {
487     $entities = $this->loadMultipleOverrideFree([$id]);
488     return isset($entities[$id]) ? $entities[$id] : NULL;
489   }
490
491   /**
492    * {@inheritdoc}
493    */
494   public function loadMultipleOverrideFree(array $ids = NULL) {
495     $this->overrideFree = TRUE;
496     $entities = $this->loadMultiple($ids);
497     $this->overrideFree = FALSE;
498     return $entities;
499   }
500
501 }