EntityStorageBase.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. <?php
  2. namespace Drupal\Core\Entity;
  3. use Drupal\Core\Entity\Query\QueryInterface;
  4. use Drupal\Core\Cache\MemoryCache\MemoryCacheInterface;
  5. /**
  6. * A base entity storage class.
  7. */
  8. abstract class EntityStorageBase extends EntityHandlerBase implements EntityStorageInterface, EntityHandlerInterface {
  9. /**
  10. * Entity type ID for this storage.
  11. *
  12. * @var string
  13. */
  14. protected $entityTypeId;
  15. /**
  16. * Information about the entity type.
  17. *
  18. * The following code returns the same object:
  19. * @code
  20. * \Drupal::entityTypeManager()->getDefinition($this->entityTypeId)
  21. * @endcode
  22. *
  23. * @var \Drupal\Core\Entity\EntityTypeInterface
  24. */
  25. protected $entityType;
  26. /**
  27. * Name of the entity's ID field in the entity database table.
  28. *
  29. * @var string
  30. */
  31. protected $idKey;
  32. /**
  33. * Name of entity's UUID database table field, if it supports UUIDs.
  34. *
  35. * Has the value FALSE if this entity does not use UUIDs.
  36. *
  37. * @var string
  38. */
  39. protected $uuidKey;
  40. /**
  41. * The name of the entity langcode property.
  42. *
  43. * @var string
  44. */
  45. protected $langcodeKey;
  46. /**
  47. * The UUID service.
  48. *
  49. * @var \Drupal\Component\Uuid\UuidInterface
  50. */
  51. protected $uuidService;
  52. /**
  53. * Name of the entity class.
  54. *
  55. * @var string
  56. */
  57. protected $entityClass;
  58. /**
  59. * The memory cache.
  60. *
  61. * @var \Drupal\Core\Cache\MemoryCache\MemoryCacheInterface
  62. */
  63. protected $memoryCache;
  64. /**
  65. * The memory cache cache tag.
  66. *
  67. * @var string
  68. */
  69. protected $memoryCacheTag;
  70. /**
  71. * Constructs an EntityStorageBase instance.
  72. *
  73. * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  74. * The entity type definition.
  75. * @param \Drupal\Core\Cache\MemoryCache\MemoryCacheInterface|null $memory_cache
  76. * The memory cache.
  77. */
  78. public function __construct(EntityTypeInterface $entity_type, MemoryCacheInterface $memory_cache = NULL) {
  79. $this->entityTypeId = $entity_type->id();
  80. $this->entityType = $entity_type;
  81. $this->idKey = $this->entityType->getKey('id');
  82. $this->uuidKey = $this->entityType->getKey('uuid');
  83. $this->langcodeKey = $this->entityType->getKey('langcode');
  84. $this->entityClass = $this->entityType->getClass();
  85. if (!isset($memory_cache)) {
  86. @trigger_error('The $memory_cache parameter was added in Drupal 8.6.x and will be required in 9.0.0. See https://www.drupal.org/node/2973262', E_USER_DEPRECATED);
  87. $memory_cache = \Drupal::service('entity.memory_cache');
  88. }
  89. $this->memoryCache = $memory_cache;
  90. $this->memoryCacheTag = 'entity.memory_cache:' . $this->entityTypeId;
  91. }
  92. /**
  93. * {@inheritdoc}
  94. */
  95. public function getEntityTypeId() {
  96. return $this->entityTypeId;
  97. }
  98. /**
  99. * {@inheritdoc}
  100. */
  101. public function getEntityType() {
  102. return $this->entityType;
  103. }
  104. /**
  105. * Builds the cache ID for the passed in entity ID.
  106. *
  107. * @param int $id
  108. * Entity ID for which the cache ID should be built.
  109. *
  110. * @return string
  111. * Cache ID that can be passed to the cache backend.
  112. */
  113. protected function buildCacheId($id) {
  114. return "values:{$this->entityTypeId}:$id";
  115. }
  116. /**
  117. * {@inheritdoc}
  118. */
  119. public function loadUnchanged($id) {
  120. $this->resetCache([$id]);
  121. return $this->load($id);
  122. }
  123. /**
  124. * {@inheritdoc}
  125. */
  126. public function resetCache(array $ids = NULL) {
  127. if ($this->entityType->isStaticallyCacheable() && isset($ids)) {
  128. foreach ($ids as $id) {
  129. $this->memoryCache->delete($this->buildCacheId($id));
  130. }
  131. }
  132. else {
  133. // Call the backend method directly.
  134. $this->memoryCache->invalidateTags([$this->memoryCacheTag]);
  135. }
  136. }
  137. /**
  138. * Gets entities from the static cache.
  139. *
  140. * @param array $ids
  141. * If not empty, return entities that match these IDs.
  142. *
  143. * @return \Drupal\Core\Entity\EntityInterface[]
  144. * Array of entities from the entity cache, keyed by entity ID.
  145. */
  146. protected function getFromStaticCache(array $ids) {
  147. $entities = [];
  148. // Load any available entities from the internal cache.
  149. if ($this->entityType->isStaticallyCacheable()) {
  150. foreach ($ids as $id) {
  151. if ($cached = $this->memoryCache->get($this->buildCacheId($id))) {
  152. $entities[$id] = $cached->data;
  153. }
  154. }
  155. }
  156. return $entities;
  157. }
  158. /**
  159. * Stores entities in the static entity cache.
  160. *
  161. * @param \Drupal\Core\Entity\EntityInterface[] $entities
  162. * Entities to store in the cache.
  163. */
  164. protected function setStaticCache(array $entities) {
  165. if ($this->entityType->isStaticallyCacheable()) {
  166. foreach ($entities as $id => $entity) {
  167. $this->memoryCache->set($this->buildCacheId($entity->id()), $entity, MemoryCacheInterface::CACHE_PERMANENT, [$this->memoryCacheTag]);
  168. }
  169. }
  170. }
  171. /**
  172. * Invokes a hook on behalf of the entity.
  173. *
  174. * @param string $hook
  175. * One of 'create', 'presave', 'insert', 'update', 'predelete', 'delete', or
  176. * 'revision_delete'.
  177. * @param \Drupal\Core\Entity\EntityInterface $entity
  178. * The entity object.
  179. */
  180. protected function invokeHook($hook, EntityInterface $entity) {
  181. // Invoke the hook.
  182. $this->moduleHandler()->invokeAll($this->entityTypeId . '_' . $hook, [$entity]);
  183. // Invoke the respective entity-level hook.
  184. $this->moduleHandler()->invokeAll('entity_' . $hook, [$entity]);
  185. }
  186. /**
  187. * {@inheritdoc}
  188. */
  189. public function create(array $values = []) {
  190. $entity_class = $this->entityClass;
  191. $entity_class::preCreate($this, $values);
  192. // Assign a new UUID if there is none yet.
  193. if ($this->uuidKey && $this->uuidService && !isset($values[$this->uuidKey])) {
  194. $values[$this->uuidKey] = $this->uuidService->generate();
  195. }
  196. $entity = $this->doCreate($values);
  197. $entity->enforceIsNew();
  198. $entity->postCreate($this);
  199. // Modules might need to add or change the data initially held by the new
  200. // entity object, for instance to fill-in default values.
  201. $this->invokeHook('create', $entity);
  202. return $entity;
  203. }
  204. /**
  205. * Performs storage-specific creation of entities.
  206. *
  207. * @param array $values
  208. * An array of values to set, keyed by property name.
  209. *
  210. * @return \Drupal\Core\Entity\EntityInterface
  211. */
  212. protected function doCreate(array $values) {
  213. return new $this->entityClass($values, $this->entityTypeId);
  214. }
  215. /**
  216. * {@inheritdoc}
  217. */
  218. public function load($id) {
  219. assert(!is_null($id), sprintf('Cannot load the "%s" entity with NULL ID.', $this->entityTypeId));
  220. $entities = $this->loadMultiple([$id]);
  221. return isset($entities[$id]) ? $entities[$id] : NULL;
  222. }
  223. /**
  224. * {@inheritdoc}
  225. */
  226. public function loadMultiple(array $ids = NULL) {
  227. $entities = [];
  228. $preloaded_entities = [];
  229. // Create a new variable which is either a prepared version of the $ids
  230. // array for later comparison with the entity cache, or FALSE if no $ids
  231. // were passed. The $ids array is reduced as items are loaded from cache,
  232. // and we need to know if it is empty for this reason to avoid querying the
  233. // database when all requested entities are loaded from cache.
  234. $flipped_ids = $ids ? array_flip($ids) : FALSE;
  235. // Try to load entities from the static cache, if the entity type supports
  236. // static caching.
  237. if ($ids) {
  238. $entities += $this->getFromStaticCache($ids);
  239. // If any entities were loaded, remove them from the IDs still to load.
  240. $ids = array_keys(array_diff_key($flipped_ids, $entities));
  241. }
  242. // Try to gather any remaining entities from a 'preload' method. This method
  243. // can invoke a hook to be used by modules that need, for example, to swap
  244. // the default revision of an entity with a different one. Even though the
  245. // base entity storage class does not actually invoke any preload hooks, we
  246. // need to call the method here so we can add the pre-loaded entity objects
  247. // to the static cache below. If all the entities were fetched from the
  248. // static cache, skip this step.
  249. if ($ids === NULL || $ids) {
  250. $preloaded_entities = $this->preLoad($ids);
  251. }
  252. if (!empty($preloaded_entities)) {
  253. $entities += $preloaded_entities;
  254. // If any entities were pre-loaded, remove them from the IDs still to
  255. // load.
  256. $ids = array_keys(array_diff_key($flipped_ids, $entities));
  257. // Add pre-loaded entities to the cache.
  258. $this->setStaticCache($preloaded_entities);
  259. }
  260. // Load any remaining entities from the database. This is the case if $ids
  261. // is set to NULL (so we load all entities) or if there are any IDs left to
  262. // load.
  263. if ($ids === NULL || $ids) {
  264. $queried_entities = $this->doLoadMultiple($ids);
  265. }
  266. // Pass all entities loaded from the database through $this->postLoad(),
  267. // which attaches fields (if supported by the entity type) and calls the
  268. // entity type specific load callback, for example hook_node_load().
  269. if (!empty($queried_entities)) {
  270. $this->postLoad($queried_entities);
  271. $entities += $queried_entities;
  272. // Add queried entities to the cache.
  273. $this->setStaticCache($queried_entities);
  274. }
  275. // Ensure that the returned array is ordered the same as the original
  276. // $ids array if this was passed in and remove any invalid IDs.
  277. if ($flipped_ids) {
  278. // Remove any invalid IDs from the array and preserve the order passed in.
  279. $flipped_ids = array_intersect_key($flipped_ids, $entities);
  280. $entities = array_replace($flipped_ids, $entities);
  281. }
  282. return $entities;
  283. }
  284. /**
  285. * Performs storage-specific loading of entities.
  286. *
  287. * Override this method to add custom functionality directly after loading.
  288. * This is always called, while self::postLoad() is only called when there are
  289. * actual results.
  290. *
  291. * @param array|null $ids
  292. * (optional) An array of entity IDs, or NULL to load all entities.
  293. *
  294. * @return \Drupal\Core\Entity\EntityInterface[]
  295. * Associative array of entities, keyed on the entity ID.
  296. */
  297. abstract protected function doLoadMultiple(array $ids = NULL);
  298. /**
  299. * Gathers entities from a 'preload' step.
  300. *
  301. * @param array|null &$ids
  302. * If not empty, return entities that match these IDs. IDs that were found
  303. * will be removed from the list.
  304. *
  305. * @return \Drupal\Core\Entity\EntityInterface[]
  306. * Associative array of entities, keyed by the entity ID.
  307. */
  308. protected function preLoad(array &$ids = NULL) {
  309. return [];
  310. }
  311. /**
  312. * Attaches data to entities upon loading.
  313. *
  314. * @param array $entities
  315. * Associative array of query results, keyed on the entity ID.
  316. */
  317. protected function postLoad(array &$entities) {
  318. $entity_class = $this->entityClass;
  319. $entity_class::postLoad($this, $entities);
  320. // Call hook_entity_load().
  321. foreach ($this->moduleHandler()->getImplementations('entity_load') as $module) {
  322. $function = $module . '_entity_load';
  323. $function($entities, $this->entityTypeId);
  324. }
  325. // Call hook_TYPE_load().
  326. foreach ($this->moduleHandler()->getImplementations($this->entityTypeId . '_load') as $module) {
  327. $function = $module . '_' . $this->entityTypeId . '_load';
  328. $function($entities);
  329. }
  330. }
  331. /**
  332. * Maps from storage records to entity objects.
  333. *
  334. * @param array $records
  335. * Associative array of query results, keyed on the entity ID.
  336. *
  337. * @return \Drupal\Core\Entity\EntityInterface[]
  338. * An array of entity objects implementing the EntityInterface.
  339. */
  340. protected function mapFromStorageRecords(array $records) {
  341. $entities = [];
  342. foreach ($records as $record) {
  343. $entity = new $this->entityClass($record, $this->entityTypeId);
  344. $entities[$entity->id()] = $entity;
  345. }
  346. return $entities;
  347. }
  348. /**
  349. * Determines if this entity already exists in storage.
  350. *
  351. * @param int|string $id
  352. * The original entity ID.
  353. * @param \Drupal\Core\Entity\EntityInterface $entity
  354. * The entity being saved.
  355. *
  356. * @return bool
  357. */
  358. abstract protected function has($id, EntityInterface $entity);
  359. /**
  360. * {@inheritdoc}
  361. */
  362. public function delete(array $entities) {
  363. if (!$entities) {
  364. // If no entities were passed, do nothing.
  365. return;
  366. }
  367. // Ensure that the entities are keyed by ID.
  368. $keyed_entities = [];
  369. foreach ($entities as $entity) {
  370. $keyed_entities[$entity->id()] = $entity;
  371. }
  372. // Allow code to run before deleting.
  373. $entity_class = $this->entityClass;
  374. $entity_class::preDelete($this, $keyed_entities);
  375. foreach ($keyed_entities as $entity) {
  376. $this->invokeHook('predelete', $entity);
  377. }
  378. // Perform the delete and reset the static cache for the deleted entities.
  379. $this->doDelete($keyed_entities);
  380. $this->resetCache(array_keys($keyed_entities));
  381. // Allow code to run after deleting.
  382. $entity_class::postDelete($this, $keyed_entities);
  383. foreach ($keyed_entities as $entity) {
  384. $this->invokeHook('delete', $entity);
  385. }
  386. }
  387. /**
  388. * Performs storage-specific entity deletion.
  389. *
  390. * @param \Drupal\Core\Entity\EntityInterface[] $entities
  391. * An array of entity objects to delete.
  392. */
  393. abstract protected function doDelete($entities);
  394. /**
  395. * {@inheritdoc}
  396. */
  397. public function save(EntityInterface $entity) {
  398. // Track if this entity is new.
  399. $is_new = $entity->isNew();
  400. // Execute presave logic and invoke the related hooks.
  401. $id = $this->doPreSave($entity);
  402. // Perform the save and reset the static cache for the changed entity.
  403. $return = $this->doSave($id, $entity);
  404. // Execute post save logic and invoke the related hooks.
  405. $this->doPostSave($entity, !$is_new);
  406. return $return;
  407. }
  408. /**
  409. * Performs presave entity processing.
  410. *
  411. * @param \Drupal\Core\Entity\EntityInterface $entity
  412. * The saved entity.
  413. *
  414. * @return int|string
  415. * The processed entity identifier.
  416. *
  417. * @throws \Drupal\Core\Entity\EntityStorageException
  418. * If the entity identifier is invalid.
  419. */
  420. protected function doPreSave(EntityInterface $entity) {
  421. $id = $entity->id();
  422. // Track the original ID.
  423. if ($entity->getOriginalId() !== NULL) {
  424. $id = $entity->getOriginalId();
  425. }
  426. // Track if this entity exists already.
  427. $id_exists = $this->has($id, $entity);
  428. // A new entity should not already exist.
  429. if ($id_exists && $entity->isNew()) {
  430. throw new EntityStorageException("'{$this->entityTypeId}' entity with ID '$id' already exists.");
  431. }
  432. // Load the original entity, if any.
  433. if ($id_exists && !isset($entity->original)) {
  434. $entity->original = $this->loadUnchanged($id);
  435. }
  436. // Allow code to run before saving.
  437. $entity->preSave($this);
  438. $this->invokeHook('presave', $entity);
  439. return $id;
  440. }
  441. /**
  442. * Performs storage-specific saving of the entity.
  443. *
  444. * @param int|string $id
  445. * The original entity ID.
  446. * @param \Drupal\Core\Entity\EntityInterface $entity
  447. * The entity to save.
  448. *
  449. * @return bool|int
  450. * If the record insert or update failed, returns FALSE. If it succeeded,
  451. * returns SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
  452. */
  453. abstract protected function doSave($id, EntityInterface $entity);
  454. /**
  455. * Performs post save entity processing.
  456. *
  457. * @param \Drupal\Core\Entity\EntityInterface $entity
  458. * The saved entity.
  459. * @param bool $update
  460. * Specifies whether the entity is being updated or created.
  461. */
  462. protected function doPostSave(EntityInterface $entity, $update) {
  463. $this->resetCache([$entity->id()]);
  464. // The entity is no longer new.
  465. $entity->enforceIsNew(FALSE);
  466. // Allow code to run after saving.
  467. $entity->postSave($this, $update);
  468. $this->invokeHook($update ? 'update' : 'insert', $entity);
  469. // After saving, this is now the "original entity", and subsequent saves
  470. // will be updates instead of inserts, and updates must always be able to
  471. // correctly identify the original entity.
  472. $entity->setOriginalId($entity->id());
  473. unset($entity->original);
  474. }
  475. /**
  476. * {@inheritdoc}
  477. */
  478. public function restore(EntityInterface $entity) {
  479. // The restore process does not invoke any pre or post-save operations.
  480. $this->doSave($entity->id(), $entity);
  481. }
  482. /**
  483. * Builds an entity query.
  484. *
  485. * @param \Drupal\Core\Entity\Query\QueryInterface $entity_query
  486. * EntityQuery instance.
  487. * @param array $values
  488. * An associative array of properties of the entity, where the keys are the
  489. * property names and the values are the values those properties must have.
  490. */
  491. protected function buildPropertyQuery(QueryInterface $entity_query, array $values) {
  492. foreach ($values as $name => $value) {
  493. // Cast scalars to array so we can consistently use an IN condition.
  494. $entity_query->condition($name, (array) $value, 'IN');
  495. }
  496. }
  497. /**
  498. * {@inheritdoc}
  499. */
  500. public function loadByProperties(array $values = []) {
  501. // Build a query to fetch the entity IDs.
  502. $entity_query = $this->getQuery();
  503. $entity_query->accessCheck(FALSE);
  504. $this->buildPropertyQuery($entity_query, $values);
  505. $result = $entity_query->execute();
  506. return $result ? $this->loadMultiple($result) : [];
  507. }
  508. /**
  509. * {@inheritdoc}
  510. */
  511. public function hasData() {
  512. return (bool) $this->getQuery()
  513. ->accessCheck(FALSE)
  514. ->range(0, 1)
  515. ->execute();
  516. }
  517. /**
  518. * {@inheritdoc}
  519. */
  520. public function getQuery($conjunction = 'AND') {
  521. // Access the service directly rather than entity.query factory so the
  522. // storage's current entity type is used.
  523. return \Drupal::service($this->getQueryServiceName())->get($this->entityType, $conjunction);
  524. }
  525. /**
  526. * {@inheritdoc}
  527. */
  528. public function getAggregateQuery($conjunction = 'AND') {
  529. // Access the service directly rather than entity.query factory so the
  530. // storage's current entity type is used.
  531. return \Drupal::service($this->getQueryServiceName())->getAggregate($this->entityType, $conjunction);
  532. }
  533. /**
  534. * Gets the name of the service for the query for this entity storage.
  535. *
  536. * @return string
  537. * The name of the service for the query for this entity storage.
  538. */
  539. abstract protected function getQueryServiceName();
  540. }