KeyValueEntityStorage.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. <?php
  2. namespace Drupal\Core\Entity\KeyValueStore;
  3. use Drupal\Component\Uuid\UuidInterface;
  4. use Drupal\Core\Cache\MemoryCache\MemoryCacheInterface;
  5. use Drupal\Core\Config\Entity\Exception\ConfigEntityIdLengthException;
  6. use Drupal\Core\Entity\FieldableEntityInterface;
  7. use Drupal\Core\Entity\EntityInterface;
  8. use Drupal\Core\Entity\EntityMalformedException;
  9. use Drupal\Core\Entity\EntityStorageBase;
  10. use Drupal\Core\Entity\EntityTypeInterface;
  11. use Drupal\Core\KeyValueStore\KeyValueStoreInterface;
  12. use Drupal\Core\Language\LanguageManagerInterface;
  13. use Symfony\Component\DependencyInjection\ContainerInterface;
  14. /**
  15. * Provides a key value backend for entities.
  16. *
  17. * @todo Entities that depend on auto-incrementing serial IDs need to explicitly
  18. * provide an ID until a generic wrapper around the functionality provided by
  19. * \Drupal\Core\Database\Connection::nextId() is added and used.
  20. * @todo Revisions are currently not supported.
  21. */
  22. class KeyValueEntityStorage extends EntityStorageBase {
  23. /**
  24. * Length limit of the entity ID.
  25. */
  26. const MAX_ID_LENGTH = 128;
  27. /**
  28. * The key value store.
  29. *
  30. * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
  31. */
  32. protected $keyValueStore;
  33. /**
  34. * The UUID service.
  35. *
  36. * @var \Drupal\Component\Uuid\UuidInterface
  37. */
  38. protected $uuidService;
  39. /**
  40. * The language manager.
  41. *
  42. * @var \Drupal\Core\Language\LanguageManagerInterface
  43. */
  44. protected $languageManager;
  45. /**
  46. * Constructs a new KeyValueEntityStorage.
  47. *
  48. * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  49. * The entity type.
  50. * @param \Drupal\Core\KeyValueStore\KeyValueStoreInterface $key_value_store
  51. * The key value store.
  52. * @param \Drupal\Component\Uuid\UuidInterface $uuid_service
  53. * The UUID service.
  54. * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
  55. * The language manager.
  56. * @param \Drupal\Core\Cache\MemoryCache\MemoryCacheInterface $memory_cache
  57. * The memory cache.
  58. */
  59. public function __construct(EntityTypeInterface $entity_type, KeyValueStoreInterface $key_value_store, UuidInterface $uuid_service, LanguageManagerInterface $language_manager, MemoryCacheInterface $memory_cache = NULL) {
  60. parent::__construct($entity_type, $memory_cache);
  61. $this->keyValueStore = $key_value_store;
  62. $this->uuidService = $uuid_service;
  63. $this->languageManager = $language_manager;
  64. // Check if the entity type supports UUIDs.
  65. $this->uuidKey = $this->entityType->getKey('uuid');
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
  71. return new static(
  72. $entity_type,
  73. $container->get('keyvalue')->get('entity_storage__' . $entity_type->id()),
  74. $container->get('uuid'),
  75. $container->get('language_manager'),
  76. $container->get('entity.memory_cache')
  77. );
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function doCreate(array $values = []) {
  83. // Set default language to site default if not provided.
  84. $values += [$this->getEntityType()->getKey('langcode') => $this->languageManager->getDefaultLanguage()->getId()];
  85. $entity = new $this->entityClass($values, $this->entityTypeId);
  86. // @todo This is handled by ContentEntityStorageBase, which assumes
  87. // FieldableEntityInterface. The current approach in
  88. // https://www.drupal.org/node/1867228 improves this but does not solve it
  89. // completely.
  90. if ($entity instanceof FieldableEntityInterface) {
  91. foreach ($entity as $name => $field) {
  92. if (isset($values[$name])) {
  93. $entity->$name = $values[$name];
  94. }
  95. elseif (!array_key_exists($name, $values)) {
  96. $entity->get($name)->applyDefaultValue();
  97. }
  98. unset($values[$name]);
  99. }
  100. }
  101. return $entity;
  102. }
  103. /**
  104. * {@inheritdoc}
  105. */
  106. public function doLoadMultiple(array $ids = NULL) {
  107. if (empty($ids)) {
  108. $entities = $this->keyValueStore->getAll();
  109. }
  110. else {
  111. $entities = $this->keyValueStore->getMultiple($ids);
  112. }
  113. return $this->mapFromStorageRecords($entities);
  114. }
  115. /**
  116. * {@inheritdoc}
  117. */
  118. public function loadRevision($revision_id) {
  119. return NULL;
  120. }
  121. /**
  122. * {@inheritdoc}
  123. */
  124. public function deleteRevision($revision_id) {
  125. return NULL;
  126. }
  127. /**
  128. * {@inheritdoc}
  129. */
  130. public function doDelete($entities) {
  131. $entity_ids = array_keys($entities);
  132. $this->keyValueStore->deleteMultiple($entity_ids);
  133. }
  134. /**
  135. * {@inheritdoc}
  136. */
  137. public function save(EntityInterface $entity) {
  138. $id = $entity->id();
  139. if ($id === NULL || $id === '') {
  140. throw new EntityMalformedException('The entity does not have an ID.');
  141. }
  142. // Check the entity ID length.
  143. // @todo This is not config-specific, but serial IDs will likely never hit
  144. // this limit. Consider renaming the exception class.
  145. if (strlen($entity->id()) > static::MAX_ID_LENGTH) {
  146. throw new ConfigEntityIdLengthException("Entity ID {$entity->id()} exceeds maximum allowed length of " . static::MAX_ID_LENGTH . ' characters.');
  147. }
  148. return parent::save($entity);
  149. }
  150. /**
  151. * {@inheritdoc}
  152. */
  153. protected function doSave($id, EntityInterface $entity) {
  154. $is_new = $entity->isNew();
  155. // Save the entity data in the key value store.
  156. $this->keyValueStore->set($entity->id(), $entity->toArray());
  157. // If this is a rename, delete the original entity.
  158. if ($this->has($id, $entity) && $id !== $entity->id()) {
  159. $this->keyValueStore->delete($id);
  160. }
  161. return $is_new ? SAVED_NEW : SAVED_UPDATED;
  162. }
  163. /**
  164. * {@inheritdoc}
  165. */
  166. protected function has($id, EntityInterface $entity) {
  167. return $this->keyValueStore->has($id);
  168. }
  169. /**
  170. * {@inheritdoc}
  171. */
  172. public function hasData() {
  173. return (bool) $this->keyValueStore->getAll();
  174. }
  175. /**
  176. * {@inheritdoc}
  177. */
  178. protected function getQueryServiceName() {
  179. return 'entity.query.keyvalue';
  180. }
  181. }