EntityStorageBase.php 15 KB

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