EntityStorageBase.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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::entityManager()->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.
  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. $entities = $this->loadMultiple([$id]);
  220. return isset($entities[$id]) ? $entities[$id] : NULL;
  221. }
  222. /**
  223. * {@inheritdoc}
  224. */
  225. public function loadMultiple(array $ids = NULL) {
  226. $entities = [];
  227. // Create a new variable which is either a prepared version of the $ids
  228. // array for later comparison with the entity cache, or FALSE if no $ids
  229. // were passed. The $ids array is reduced as items are loaded from cache,
  230. // and we need to know if it's empty for this reason to avoid querying the
  231. // database when all requested entities are loaded from cache.
  232. $passed_ids = !empty($ids) ? array_flip($ids) : FALSE;
  233. // Try to load entities from the static cache, if the entity type supports
  234. // static caching.
  235. if ($this->entityType->isStaticallyCacheable() && $ids) {
  236. $entities += $this->getFromStaticCache($ids);
  237. // If any entities were loaded, remove them from the ids still to load.
  238. if ($passed_ids) {
  239. $ids = array_keys(array_diff_key($passed_ids, $entities));
  240. }
  241. }
  242. // Load any remaining entities from the database. This is the case if $ids
  243. // is set to NULL (so we load all entities) or if there are any ids left to
  244. // load.
  245. if ($ids === NULL || $ids) {
  246. $queried_entities = $this->doLoadMultiple($ids);
  247. }
  248. // Pass all entities loaded from the database through $this->postLoad(),
  249. // which attaches fields (if supported by the entity type) and calls the
  250. // entity type specific load callback, for example hook_node_load().
  251. if (!empty($queried_entities)) {
  252. $this->postLoad($queried_entities);
  253. $entities += $queried_entities;
  254. }
  255. if ($this->entityType->isStaticallyCacheable()) {
  256. // Add entities to the cache.
  257. if (!empty($queried_entities)) {
  258. $this->setStaticCache($queried_entities);
  259. }
  260. }
  261. // Ensure that the returned array is ordered the same as the original
  262. // $ids array if this was passed in and remove any invalid ids.
  263. if ($passed_ids) {
  264. // Remove any invalid ids from the array.
  265. $passed_ids = array_intersect_key($passed_ids, $entities);
  266. foreach ($entities as $entity) {
  267. $passed_ids[$entity->id()] = $entity;
  268. }
  269. $entities = $passed_ids;
  270. }
  271. return $entities;
  272. }
  273. /**
  274. * Performs storage-specific loading of entities.
  275. *
  276. * Override this method to add custom functionality directly after loading.
  277. * This is always called, while self::postLoad() is only called when there are
  278. * actual results.
  279. *
  280. * @param array|null $ids
  281. * (optional) An array of entity IDs, or NULL to load all entities.
  282. *
  283. * @return \Drupal\Core\Entity\EntityInterface[]
  284. * Associative array of entities, keyed on the entity ID.
  285. */
  286. abstract protected function doLoadMultiple(array $ids = NULL);
  287. /**
  288. * Attaches data to entities upon loading.
  289. *
  290. * @param array $entities
  291. * Associative array of query results, keyed on the entity ID.
  292. */
  293. protected function postLoad(array &$entities) {
  294. $entity_class = $this->entityClass;
  295. $entity_class::postLoad($this, $entities);
  296. // Call hook_entity_load().
  297. foreach ($this->moduleHandler()->getImplementations('entity_load') as $module) {
  298. $function = $module . '_entity_load';
  299. $function($entities, $this->entityTypeId);
  300. }
  301. // Call hook_TYPE_load().
  302. foreach ($this->moduleHandler()->getImplementations($this->entityTypeId . '_load') as $module) {
  303. $function = $module . '_' . $this->entityTypeId . '_load';
  304. $function($entities);
  305. }
  306. }
  307. /**
  308. * Maps from storage records to entity objects.
  309. *
  310. * @param array $records
  311. * Associative array of query results, keyed on the entity ID.
  312. *
  313. * @return \Drupal\Core\Entity\EntityInterface[]
  314. * An array of entity objects implementing the EntityInterface.
  315. */
  316. protected function mapFromStorageRecords(array $records) {
  317. $entities = [];
  318. foreach ($records as $record) {
  319. $entity = new $this->entityClass($record, $this->entityTypeId);
  320. $entities[$entity->id()] = $entity;
  321. }
  322. return $entities;
  323. }
  324. /**
  325. * Determines if this entity already exists in storage.
  326. *
  327. * @param int|string $id
  328. * The original entity ID.
  329. * @param \Drupal\Core\Entity\EntityInterface $entity
  330. * The entity being saved.
  331. *
  332. * @return bool
  333. */
  334. abstract protected function has($id, EntityInterface $entity);
  335. /**
  336. * {@inheritdoc}
  337. */
  338. public function delete(array $entities) {
  339. if (!$entities) {
  340. // If no entities were passed, do nothing.
  341. return;
  342. }
  343. // Ensure that the entities are keyed by ID.
  344. $keyed_entities = [];
  345. foreach ($entities as $entity) {
  346. $keyed_entities[$entity->id()] = $entity;
  347. }
  348. // Allow code to run before deleting.
  349. $entity_class = $this->entityClass;
  350. $entity_class::preDelete($this, $keyed_entities);
  351. foreach ($keyed_entities as $entity) {
  352. $this->invokeHook('predelete', $entity);
  353. }
  354. // Perform the delete and reset the static cache for the deleted entities.
  355. $this->doDelete($keyed_entities);
  356. $this->resetCache(array_keys($keyed_entities));
  357. // Allow code to run after deleting.
  358. $entity_class::postDelete($this, $keyed_entities);
  359. foreach ($keyed_entities as $entity) {
  360. $this->invokeHook('delete', $entity);
  361. }
  362. }
  363. /**
  364. * Performs storage-specific entity deletion.
  365. *
  366. * @param \Drupal\Core\Entity\EntityInterface[] $entities
  367. * An array of entity objects to delete.
  368. */
  369. abstract protected function doDelete($entities);
  370. /**
  371. * {@inheritdoc}
  372. */
  373. public function save(EntityInterface $entity) {
  374. // Track if this entity is new.
  375. $is_new = $entity->isNew();
  376. // Execute presave logic and invoke the related hooks.
  377. $id = $this->doPreSave($entity);
  378. // Perform the save and reset the static cache for the changed entity.
  379. $return = $this->doSave($id, $entity);
  380. // Execute post save logic and invoke the related hooks.
  381. $this->doPostSave($entity, !$is_new);
  382. return $return;
  383. }
  384. /**
  385. * Performs presave entity processing.
  386. *
  387. * @param \Drupal\Core\Entity\EntityInterface $entity
  388. * The saved entity.
  389. *
  390. * @return int|string
  391. * The processed entity identifier.
  392. *
  393. * @throws \Drupal\Core\Entity\EntityStorageException
  394. * If the entity identifier is invalid.
  395. */
  396. protected function doPreSave(EntityInterface $entity) {
  397. $id = $entity->id();
  398. // Track the original ID.
  399. if ($entity->getOriginalId() !== NULL) {
  400. $id = $entity->getOriginalId();
  401. }
  402. // Track if this entity exists already.
  403. $id_exists = $this->has($id, $entity);
  404. // A new entity should not already exist.
  405. if ($id_exists && $entity->isNew()) {
  406. throw new EntityStorageException("'{$this->entityTypeId}' entity with ID '$id' already exists.");
  407. }
  408. // Load the original entity, if any.
  409. if ($id_exists && !isset($entity->original)) {
  410. $entity->original = $this->loadUnchanged($id);
  411. }
  412. // Allow code to run before saving.
  413. $entity->preSave($this);
  414. $this->invokeHook('presave', $entity);
  415. return $id;
  416. }
  417. /**
  418. * Performs storage-specific saving of the entity.
  419. *
  420. * @param int|string $id
  421. * The original entity ID.
  422. * @param \Drupal\Core\Entity\EntityInterface $entity
  423. * The entity to save.
  424. *
  425. * @return bool|int
  426. * If the record insert or update failed, returns FALSE. If it succeeded,
  427. * returns SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
  428. */
  429. abstract protected function doSave($id, EntityInterface $entity);
  430. /**
  431. * Performs post save entity processing.
  432. *
  433. * @param \Drupal\Core\Entity\EntityInterface $entity
  434. * The saved entity.
  435. * @param bool $update
  436. * Specifies whether the entity is being updated or created.
  437. */
  438. protected function doPostSave(EntityInterface $entity, $update) {
  439. $this->resetCache([$entity->id()]);
  440. // The entity is no longer new.
  441. $entity->enforceIsNew(FALSE);
  442. // Allow code to run after saving.
  443. $entity->postSave($this, $update);
  444. $this->invokeHook($update ? 'update' : 'insert', $entity);
  445. // After saving, this is now the "original entity", and subsequent saves
  446. // will be updates instead of inserts, and updates must always be able to
  447. // correctly identify the original entity.
  448. $entity->setOriginalId($entity->id());
  449. unset($entity->original);
  450. }
  451. /**
  452. * Builds an entity query.
  453. *
  454. * @param \Drupal\Core\Entity\Query\QueryInterface $entity_query
  455. * EntityQuery instance.
  456. * @param array $values
  457. * An associative array of properties of the entity, where the keys are the
  458. * property names and the values are the values those properties must have.
  459. */
  460. protected function buildPropertyQuery(QueryInterface $entity_query, array $values) {
  461. foreach ($values as $name => $value) {
  462. // Cast scalars to array so we can consistently use an IN condition.
  463. $entity_query->condition($name, (array) $value, 'IN');
  464. }
  465. }
  466. /**
  467. * {@inheritdoc}
  468. */
  469. public function loadByProperties(array $values = []) {
  470. // Build a query to fetch the entity IDs.
  471. $entity_query = $this->getQuery();
  472. $entity_query->accessCheck(FALSE);
  473. $this->buildPropertyQuery($entity_query, $values);
  474. $result = $entity_query->execute();
  475. return $result ? $this->loadMultiple($result) : [];
  476. }
  477. /**
  478. * {@inheritdoc}
  479. */
  480. public function hasData() {
  481. return (bool) $this->getQuery()
  482. ->accessCheck(FALSE)
  483. ->range(0, 1)
  484. ->execute();
  485. }
  486. /**
  487. * {@inheritdoc}
  488. */
  489. public function getQuery($conjunction = 'AND') {
  490. // Access the service directly rather than entity.query factory so the
  491. // storage's current entity type is used.
  492. return \Drupal::service($this->getQueryServiceName())->get($this->entityType, $conjunction);
  493. }
  494. /**
  495. * {@inheritdoc}
  496. */
  497. public function getAggregateQuery($conjunction = 'AND') {
  498. // Access the service directly rather than entity.query factory so the
  499. // storage's current entity type is used.
  500. return \Drupal::service($this->getQueryServiceName())->getAggregate($this->entityType, $conjunction);
  501. }
  502. /**
  503. * Gets the name of the service for the query for this entity storage.
  504. *
  505. * @return string
  506. * The name of the service for the query for this entity storage.
  507. */
  508. abstract protected function getQueryServiceName();
  509. }