ContentEntityStorageBase.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. <?php
  2. namespace Drupal\Core\Entity;
  3. use Drupal\Core\Cache\Cache;
  4. use Drupal\Core\Cache\CacheBackendInterface;
  5. use Drupal\Core\Field\FieldDefinitionInterface;
  6. use Drupal\Core\Field\FieldStorageDefinitionInterface;
  7. use Drupal\Core\TypedData\TranslationStatusInterface;
  8. use Symfony\Component\DependencyInjection\ContainerInterface;
  9. /**
  10. * Base class for content entity storage handlers.
  11. */
  12. abstract class ContentEntityStorageBase extends EntityStorageBase implements ContentEntityStorageInterface, DynamicallyFieldableEntityStorageInterface {
  13. /**
  14. * The entity bundle key.
  15. *
  16. * @var string|bool
  17. */
  18. protected $bundleKey = FALSE;
  19. /**
  20. * The entity manager.
  21. *
  22. * @var \Drupal\Core\Entity\EntityManagerInterface
  23. */
  24. protected $entityManager;
  25. /**
  26. * Cache backend.
  27. *
  28. * @var \Drupal\Core\Cache\CacheBackendInterface
  29. */
  30. protected $cacheBackend;
  31. /**
  32. * Constructs a ContentEntityStorageBase object.
  33. *
  34. * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  35. * The entity type definition.
  36. * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
  37. * The entity manager.
  38. * @param \Drupal\Core\Cache\CacheBackendInterface $cache
  39. * The cache backend to be used.
  40. */
  41. public function __construct(EntityTypeInterface $entity_type, EntityManagerInterface $entity_manager, CacheBackendInterface $cache) {
  42. parent::__construct($entity_type);
  43. $this->bundleKey = $this->entityType->getKey('bundle');
  44. $this->entityManager = $entity_manager;
  45. $this->cacheBackend = $cache;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
  51. return new static(
  52. $entity_type,
  53. $container->get('entity.manager'),
  54. $container->get('cache.entity')
  55. );
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. protected function doCreate(array $values) {
  61. // We have to determine the bundle first.
  62. $bundle = FALSE;
  63. if ($this->bundleKey) {
  64. if (!isset($values[$this->bundleKey])) {
  65. throw new EntityStorageException('Missing bundle for entity type ' . $this->entityTypeId);
  66. }
  67. $bundle = $values[$this->bundleKey];
  68. }
  69. $entity = new $this->entityClass([], $this->entityTypeId, $bundle);
  70. $this->initFieldValues($entity, $values);
  71. return $entity;
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function createWithSampleValues($bundle = FALSE, array $values = []) {
  77. // ID and revision should never have sample values generated for them.
  78. $forbidden_keys = [
  79. $this->entityType->getKey('id'),
  80. ];
  81. if ($revision_key = $this->entityType->getKey('revision')) {
  82. $forbidden_keys[] = $revision_key;
  83. }
  84. if ($bundle_key = $this->entityType->getKey('bundle')) {
  85. if (!$bundle) {
  86. throw new EntityStorageException("No entity bundle was specified");
  87. }
  88. if (!array_key_exists($bundle, $this->entityManager->getBundleInfo($this->entityTypeId))) {
  89. throw new EntityStorageException(sprintf("Missing entity bundle. The \"%s\" bundle does not exist", $bundle));
  90. }
  91. $values[$bundle_key] = $bundle;
  92. // Bundle is already set
  93. $forbidden_keys[] = $bundle_key;
  94. }
  95. // Forbid sample generation on any keys whose values were submitted.
  96. $forbidden_keys = array_merge($forbidden_keys, array_keys($values));
  97. /** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */
  98. $entity = $this->create($values);
  99. foreach ($entity as $field_name => $value) {
  100. if (!in_array($field_name, $forbidden_keys, TRUE)) {
  101. $entity->get($field_name)->generateSampleItems();
  102. }
  103. }
  104. return $entity;
  105. }
  106. /**
  107. * Initializes field values.
  108. *
  109. * @param \Drupal\Core\Entity\ContentEntityInterface $entity
  110. * An entity object.
  111. * @param array $values
  112. * (optional) An associative array of initial field values keyed by field
  113. * name. If none is provided default values will be applied.
  114. * @param array $field_names
  115. * (optional) An associative array of field names to be initialized. If none
  116. * is provided all fields will be initialized.
  117. */
  118. protected function initFieldValues(ContentEntityInterface $entity, array $values = [], array $field_names = []) {
  119. // Populate field values.
  120. foreach ($entity as $name => $field) {
  121. if (!$field_names || isset($field_names[$name])) {
  122. if (isset($values[$name])) {
  123. $entity->$name = $values[$name];
  124. }
  125. elseif (!array_key_exists($name, $values)) {
  126. $entity->get($name)->applyDefaultValue();
  127. }
  128. }
  129. unset($values[$name]);
  130. }
  131. // Set any passed values for non-defined fields also.
  132. foreach ($values as $name => $value) {
  133. $entity->$name = $value;
  134. }
  135. // Make sure modules can alter field initial values.
  136. $this->invokeHook('field_values_init', $entity);
  137. }
  138. /**
  139. * Checks whether any entity revision is translated.
  140. *
  141. * @param \Drupal\Core\Entity\EntityInterface|\Drupal\Core\Entity\TranslatableInterface $entity
  142. * The entity object to be checked.
  143. *
  144. * @return bool
  145. * TRUE if the entity has at least one translation in any revision, FALSE
  146. * otherwise.
  147. *
  148. * @see \Drupal\Core\TypedData\TranslatableInterface::getTranslationLanguages()
  149. * @see \Drupal\Core\Entity\ContentEntityStorageBase::isAnyStoredRevisionTranslated()
  150. */
  151. protected function isAnyRevisionTranslated(TranslatableInterface $entity) {
  152. return $entity->getTranslationLanguages(FALSE) || $this->isAnyStoredRevisionTranslated($entity);
  153. }
  154. /**
  155. * Checks whether any stored entity revision is translated.
  156. *
  157. * A revisionable entity can have translations in a pending revision, hence
  158. * the default revision may appear as not translated. This determines whether
  159. * the entity has any translation in the storage and thus should be considered
  160. * as multilingual.
  161. *
  162. * @param \Drupal\Core\Entity\EntityInterface|\Drupal\Core\Entity\TranslatableInterface $entity
  163. * The entity object to be checked.
  164. *
  165. * @return bool
  166. * TRUE if the entity has at least one translation in any revision, FALSE
  167. * otherwise.
  168. *
  169. * @see \Drupal\Core\TypedData\TranslatableInterface::getTranslationLanguages()
  170. * @see \Drupal\Core\Entity\ContentEntityStorageBase::isAnyRevisionTranslated()
  171. */
  172. protected function isAnyStoredRevisionTranslated(TranslatableInterface $entity) {
  173. /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  174. if ($entity->isNew()) {
  175. return FALSE;
  176. }
  177. if ($entity instanceof TranslationStatusInterface) {
  178. foreach ($entity->getTranslationLanguages(FALSE) as $langcode => $language) {
  179. if ($entity->getTranslationStatus($langcode) === TranslationStatusInterface::TRANSLATION_EXISTING) {
  180. return TRUE;
  181. }
  182. }
  183. }
  184. $query = $this->getQuery()
  185. ->condition($this->entityType->getKey('id'), $entity->id())
  186. ->condition($this->entityType->getKey('default_langcode'), 0)
  187. ->accessCheck(FALSE)
  188. ->range(0, 1);
  189. if ($entity->getEntityType()->isRevisionable()) {
  190. $query->allRevisions();
  191. }
  192. $result = $query->execute();
  193. return !empty($result);
  194. }
  195. /**
  196. * {@inheritdoc}
  197. */
  198. public function createTranslation(ContentEntityInterface $entity, $langcode, array $values = []) {
  199. $translation = $entity->getTranslation($langcode);
  200. $definitions = array_filter($translation->getFieldDefinitions(), function (FieldDefinitionInterface $definition) {
  201. return $definition->isTranslatable();
  202. });
  203. $field_names = array_map(function (FieldDefinitionInterface $definition) {
  204. return $definition->getName();
  205. }, $definitions);
  206. $values[$this->langcodeKey] = $langcode;
  207. $values[$this->getEntityType()->getKey('default_langcode')] = FALSE;
  208. $this->initFieldValues($translation, $values, $field_names);
  209. $this->invokeHook('translation_create', $translation);
  210. return $translation;
  211. }
  212. /**
  213. * {@inheritdoc}
  214. */
  215. public function createRevision(RevisionableInterface $entity, $default = TRUE, $keep_untranslatable_fields = NULL) {
  216. /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  217. $new_revision = clone $entity;
  218. // For translatable entities, create a merged revision of the active
  219. // translation and the other translations in the default revision. This
  220. // permits the creation of pending revisions that can always be saved as the
  221. // new default revision without reverting changes in other languages.
  222. if (!$entity->isNew() && !$entity->isDefaultRevision() && $entity->isTranslatable() && $this->isAnyRevisionTranslated($entity)) {
  223. $active_langcode = $entity->language()->getId();
  224. $skipped_field_names = array_flip($this->getRevisionTranslationMergeSkippedFieldNames());
  225. // By default we copy untranslatable field values from the default
  226. // revision, unless they are configured to affect only the default
  227. // translation. This way we can ensure we always have only one affected
  228. // translation in pending revisions. This constraint is enforced by
  229. // EntityUntranslatableFieldsConstraintValidator.
  230. if (!isset($keep_untranslatable_fields)) {
  231. $keep_untranslatable_fields = $entity->isDefaultTranslation() && $entity->isDefaultTranslationAffectedOnly();
  232. }
  233. /** @var \Drupal\Core\Entity\ContentEntityInterface $default_revision */
  234. $default_revision = $this->load($entity->id());
  235. $translation_languages = $default_revision->getTranslationLanguages();
  236. foreach ($translation_languages as $langcode => $language) {
  237. if ($langcode == $active_langcode) {
  238. continue;
  239. }
  240. $default_revision_translation = $default_revision->getTranslation($langcode);
  241. $new_revision_translation = $new_revision->hasTranslation($langcode) ?
  242. $new_revision->getTranslation($langcode) : $new_revision->addTranslation($langcode);
  243. /** @var \Drupal\Core\Field\FieldItemListInterface[] $sync_items */
  244. $sync_items = array_diff_key(
  245. $keep_untranslatable_fields ? $default_revision_translation->getTranslatableFields() : $default_revision_translation->getFields(),
  246. $skipped_field_names
  247. );
  248. foreach ($sync_items as $field_name => $items) {
  249. $new_revision_translation->set($field_name, $items->getValue());
  250. }
  251. // Make sure the "revision_translation_affected" flag is recalculated.
  252. $new_revision_translation->setRevisionTranslationAffected(NULL);
  253. // No need to copy untranslatable field values more than once.
  254. $keep_untranslatable_fields = TRUE;
  255. }
  256. // Make sure we do not inadvertently recreate removed translations.
  257. foreach (array_diff_key($new_revision->getTranslationLanguages(), $translation_languages) as $langcode => $language) {
  258. // Allow a new revision to be created for the active language.
  259. if ($langcode !== $active_langcode) {
  260. $new_revision->removeTranslation($langcode);
  261. }
  262. }
  263. // The "original" property is used in various places to detect changes in
  264. // field values with respect to the stored ones. If the property is not
  265. // defined, the stored version is loaded explicitly. Since the merged
  266. // revision generated here is not stored anywhere, we need to populate the
  267. // "original" property manually, so that changes can be properly detected.
  268. $new_revision->original = clone $new_revision;
  269. }
  270. // Eventually mark the new revision as such.
  271. $new_revision->setNewRevision();
  272. $new_revision->isDefaultRevision($default);
  273. // Actually make sure the current translation is marked as affected, even if
  274. // there are no explicit changes, to be sure this revision can be related
  275. // to the correct translation.
  276. $new_revision->setRevisionTranslationAffected(TRUE);
  277. return $new_revision;
  278. }
  279. /**
  280. * Returns an array of field names to skip when merging revision translations.
  281. *
  282. * @return array
  283. * An array of field names.
  284. */
  285. protected function getRevisionTranslationMergeSkippedFieldNames() {
  286. /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
  287. $entity_type = $this->getEntityType();
  288. // A list of known revision metadata fields which should be skipped from
  289. // the comparision.
  290. $field_names = [
  291. $entity_type->getKey('revision'),
  292. $entity_type->getKey('revision_translation_affected'),
  293. ];
  294. $field_names = array_merge($field_names, array_values($entity_type->getRevisionMetadataKeys()));
  295. return $field_names;
  296. }
  297. /**
  298. * {@inheritdoc}
  299. */
  300. public function getLatestRevisionId($entity_id) {
  301. if (!$this->entityType->isRevisionable()) {
  302. return NULL;
  303. }
  304. $result = $this->getQuery()
  305. ->latestRevision()
  306. ->condition($this->entityType->getKey('id'), $entity_id)
  307. ->accessCheck(FALSE)
  308. ->execute();
  309. return key($result);
  310. }
  311. /**
  312. * {@inheritdoc}
  313. */
  314. public function getLatestTranslationAffectedRevisionId($entity_id, $langcode) {
  315. if (!$this->entityType->isRevisionable()) {
  316. return NULL;
  317. }
  318. if (!$this->entityType->isTranslatable()) {
  319. return $this->getLatestRevisionId($entity_id);
  320. }
  321. $result = $this->getQuery()
  322. ->allRevisions()
  323. ->condition($this->entityType->getKey('id'), $entity_id)
  324. ->condition($this->entityType->getKey('revision_translation_affected'), 1, '=', $langcode)
  325. ->range(0, 1)
  326. ->sort($this->entityType->getKey('revision'), 'DESC')
  327. ->accessCheck(FALSE)
  328. ->execute();
  329. return key($result);
  330. }
  331. /**
  332. * {@inheritdoc}
  333. */
  334. public function onFieldStorageDefinitionCreate(FieldStorageDefinitionInterface $storage_definition) {}
  335. /**
  336. * {@inheritdoc}
  337. */
  338. public function onFieldStorageDefinitionUpdate(FieldStorageDefinitionInterface $storage_definition, FieldStorageDefinitionInterface $original) {}
  339. /**
  340. * {@inheritdoc}
  341. */
  342. public function onFieldStorageDefinitionDelete(FieldStorageDefinitionInterface $storage_definition) {}
  343. /**
  344. * {@inheritdoc}
  345. */
  346. public function onFieldDefinitionCreate(FieldDefinitionInterface $field_definition) {}
  347. /**
  348. * {@inheritdoc}
  349. */
  350. public function onFieldDefinitionUpdate(FieldDefinitionInterface $field_definition, FieldDefinitionInterface $original) {}
  351. /**
  352. * {@inheritdoc}
  353. */
  354. public function onFieldDefinitionDelete(FieldDefinitionInterface $field_definition) {}
  355. /**
  356. * {@inheritdoc}
  357. */
  358. public function purgeFieldData(FieldDefinitionInterface $field_definition, $batch_size) {
  359. $items_by_entity = $this->readFieldItemsToPurge($field_definition, $batch_size);
  360. foreach ($items_by_entity as $items) {
  361. $items->delete();
  362. $this->purgeFieldItems($items->getEntity(), $field_definition);
  363. }
  364. return count($items_by_entity);
  365. }
  366. /**
  367. * Reads values to be purged for a single field.
  368. *
  369. * This method is called during field data purge, on fields for which
  370. * onFieldDefinitionDelete() has previously run.
  371. *
  372. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
  373. * The field definition.
  374. * @param $batch_size
  375. * The maximum number of field data records to purge before returning.
  376. *
  377. * @return \Drupal\Core\Field\FieldItemListInterface[]
  378. * An array of field item lists, keyed by entity revision id.
  379. */
  380. abstract protected function readFieldItemsToPurge(FieldDefinitionInterface $field_definition, $batch_size);
  381. /**
  382. * Removes field items from storage per entity during purge.
  383. *
  384. * @param ContentEntityInterface $entity
  385. * The entity revision, whose values are being purged.
  386. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
  387. * The field whose values are bing purged.
  388. */
  389. abstract protected function purgeFieldItems(ContentEntityInterface $entity, FieldDefinitionInterface $field_definition);
  390. /**
  391. * {@inheritdoc}
  392. */
  393. public function finalizePurge(FieldStorageDefinitionInterface $storage_definition) {}
  394. /**
  395. * {@inheritdoc}
  396. */
  397. public function loadRevision($revision_id) {
  398. $revisions = $this->loadMultipleRevisions([$revision_id]);
  399. return isset($revisions[$revision_id]) ? $revisions[$revision_id] : NULL;
  400. }
  401. /**
  402. * {@inheritdoc}
  403. */
  404. public function loadMultipleRevisions(array $revision_ids) {
  405. $revisions = $this->doLoadMultipleRevisionsFieldItems($revision_ids);
  406. // The hooks are executed with an array of entities keyed by the entity ID.
  407. // As we could load multiple revisions for the same entity ID at once we
  408. // have to build groups of entities where the same entity ID is present only
  409. // once.
  410. $entity_groups = [];
  411. $entity_group_mapping = [];
  412. foreach ($revisions as $revision) {
  413. $entity_id = $revision->id();
  414. $entity_group_key = isset($entity_group_mapping[$entity_id]) ? $entity_group_mapping[$entity_id] + 1 : 0;
  415. $entity_group_mapping[$entity_id] = $entity_group_key;
  416. $entity_groups[$entity_group_key][$entity_id] = $revision;
  417. }
  418. // Invoke the entity hooks for each group.
  419. foreach ($entity_groups as $entities) {
  420. $this->invokeStorageLoadHook($entities);
  421. $this->postLoad($entities);
  422. }
  423. return $revisions;
  424. }
  425. /**
  426. * Actually loads revision field item values from the storage.
  427. *
  428. * @param int|string $revision_id
  429. * The revision identifier.
  430. *
  431. * @return \Drupal\Core\Entity\EntityInterface|null
  432. * The specified entity revision or NULL if not found.
  433. *
  434. * @deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.0.
  435. * \Drupal\Core\Entity\ContentEntityStorageBase::doLoadMultipleRevisionsFieldItems()
  436. * should be implemented instead.
  437. *
  438. * @see https://www.drupal.org/node/2924915
  439. */
  440. abstract protected function doLoadRevisionFieldItems($revision_id);
  441. /**
  442. * Actually loads revision field item values from the storage.
  443. *
  444. * @param array $revision_ids
  445. * An array of revision identifiers.
  446. *
  447. * @return \Drupal\Core\Entity\EntityInterface[]
  448. * The specified entity revisions or an empty array if none are found.
  449. */
  450. protected function doLoadMultipleRevisionsFieldItems($revision_ids) {
  451. $revisions = [];
  452. foreach ($revision_ids as $revision_id) {
  453. $revisions[] = $this->doLoadRevisionFieldItems($revision_id);
  454. }
  455. return $revisions;
  456. }
  457. /**
  458. * {@inheritdoc}
  459. */
  460. protected function doSave($id, EntityInterface $entity) {
  461. /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  462. if ($entity->isNew()) {
  463. // Ensure the entity is still seen as new after assigning it an id, while
  464. // storing its data.
  465. $entity->enforceIsNew();
  466. if ($this->entityType->isRevisionable()) {
  467. $entity->setNewRevision();
  468. }
  469. $return = SAVED_NEW;
  470. }
  471. else {
  472. // @todo Consider returning a different value when saving a non-default
  473. // entity revision. See https://www.drupal.org/node/2509360.
  474. $return = $entity->isDefaultRevision() ? SAVED_UPDATED : FALSE;
  475. }
  476. $this->populateAffectedRevisionTranslations($entity);
  477. // Populate the "revision_default" flag. We skip this when we are resaving
  478. // the revision because this is only allowed for default revisions, and
  479. // these cannot be made non-default.
  480. if ($this->entityType->isRevisionable() && $entity->isNewRevision()) {
  481. $revision_default_key = $this->entityType->getRevisionMetadataKey('revision_default');
  482. $entity->set($revision_default_key, $entity->isDefaultRevision());
  483. }
  484. $this->doSaveFieldItems($entity);
  485. return $return;
  486. }
  487. /**
  488. * Writes entity field values to the storage.
  489. *
  490. * This method is responsible for allocating entity and revision identifiers
  491. * and updating the entity object with their values.
  492. *
  493. * @param \Drupal\Core\Entity\ContentEntityInterface $entity
  494. * The entity object.
  495. * @param string[] $names
  496. * (optional) The name of the fields to be written to the storage. If an
  497. * empty value is passed all field values are saved.
  498. */
  499. abstract protected function doSaveFieldItems(ContentEntityInterface $entity, array $names = []);
  500. /**
  501. * {@inheritdoc}
  502. */
  503. protected function doPreSave(EntityInterface $entity) {
  504. /** @var \Drupal\Core\Entity\ContentEntityBase $entity */
  505. // Sync the changes made in the fields array to the internal values array.
  506. $entity->updateOriginalValues();
  507. if ($entity->getEntityType()->isRevisionable() && !$entity->isNew() && empty($entity->getLoadedRevisionId())) {
  508. // Update the loaded revision id for rare special cases when no loaded
  509. // revision is given when updating an existing entity. This for example
  510. // happens when calling save() in hook_entity_insert().
  511. $entity->updateLoadedRevisionId();
  512. }
  513. $id = parent::doPreSave($entity);
  514. if (!$entity->isNew()) {
  515. // If the ID changed then original can't be loaded, throw an exception
  516. // in that case.
  517. if (empty($entity->original) || $entity->id() != $entity->original->id()) {
  518. throw new EntityStorageException("Update existing '{$this->entityTypeId}' entity while changing the ID is not supported.");
  519. }
  520. // Do not allow changing the revision ID when resaving the current
  521. // revision.
  522. if (!$entity->isNewRevision() && $entity->getRevisionId() != $entity->getLoadedRevisionId()) {
  523. throw new EntityStorageException("Update existing '{$this->entityTypeId}' entity revision while changing the revision ID is not supported.");
  524. }
  525. }
  526. return $id;
  527. }
  528. /**
  529. * {@inheritdoc}
  530. */
  531. protected function doPostSave(EntityInterface $entity, $update) {
  532. /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  533. if ($update && $this->entityType->isTranslatable()) {
  534. $this->invokeTranslationHooks($entity);
  535. }
  536. parent::doPostSave($entity, $update);
  537. // The revision is stored, it should no longer be marked as new now.
  538. if ($this->entityType->isRevisionable()) {
  539. $entity->updateLoadedRevisionId();
  540. $entity->setNewRevision(FALSE);
  541. }
  542. }
  543. /**
  544. * {@inheritdoc}
  545. */
  546. protected function doDelete($entities) {
  547. /** @var \Drupal\Core\Entity\ContentEntityInterface[] $entities */
  548. foreach ($entities as $entity) {
  549. $this->invokeFieldMethod('delete', $entity);
  550. }
  551. $this->doDeleteFieldItems($entities);
  552. }
  553. /**
  554. * Deletes entity field values from the storage.
  555. *
  556. * @param \Drupal\Core\Entity\ContentEntityInterface[] $entities
  557. * An array of entity objects to be deleted.
  558. */
  559. abstract protected function doDeleteFieldItems($entities);
  560. /**
  561. * {@inheritdoc}
  562. */
  563. public function deleteRevision($revision_id) {
  564. /** @var \Drupal\Core\Entity\ContentEntityInterface $revision */
  565. if ($revision = $this->loadRevision($revision_id)) {
  566. // Prevent deletion if this is the default revision.
  567. if ($revision->isDefaultRevision()) {
  568. throw new EntityStorageException('Default revision can not be deleted');
  569. }
  570. $this->invokeFieldMethod('deleteRevision', $revision);
  571. $this->doDeleteRevisionFieldItems($revision);
  572. $this->invokeHook('revision_delete', $revision);
  573. }
  574. }
  575. /**
  576. * Deletes field values of an entity revision from the storage.
  577. *
  578. * @param \Drupal\Core\Entity\ContentEntityInterface $revision
  579. * An entity revision object to be deleted.
  580. */
  581. abstract protected function doDeleteRevisionFieldItems(ContentEntityInterface $revision);
  582. /**
  583. * Checks translation statuses and invoke the related hooks if needed.
  584. *
  585. * @param \Drupal\Core\Entity\ContentEntityInterface $entity
  586. * The entity being saved.
  587. */
  588. protected function invokeTranslationHooks(ContentEntityInterface $entity) {
  589. $translations = $entity->getTranslationLanguages(FALSE);
  590. $original_translations = $entity->original->getTranslationLanguages(FALSE);
  591. $all_translations = array_keys($translations + $original_translations);
  592. // Notify modules of translation insertion/deletion.
  593. foreach ($all_translations as $langcode) {
  594. if (isset($translations[$langcode]) && !isset($original_translations[$langcode])) {
  595. $this->invokeHook('translation_insert', $entity->getTranslation($langcode));
  596. }
  597. elseif (!isset($translations[$langcode]) && isset($original_translations[$langcode])) {
  598. $this->invokeHook('translation_delete', $entity->original->getTranslation($langcode));
  599. }
  600. }
  601. }
  602. /**
  603. * Invokes hook_entity_storage_load().
  604. *
  605. * @param \Drupal\Core\Entity\ContentEntityInterface[] $entities
  606. * List of entities, keyed on the entity ID.
  607. */
  608. protected function invokeStorageLoadHook(array &$entities) {
  609. if (!empty($entities)) {
  610. // Call hook_entity_storage_load().
  611. foreach ($this->moduleHandler()->getImplementations('entity_storage_load') as $module) {
  612. $function = $module . '_entity_storage_load';
  613. $function($entities, $this->entityTypeId);
  614. }
  615. // Call hook_TYPE_storage_load().
  616. foreach ($this->moduleHandler()->getImplementations($this->entityTypeId . '_storage_load') as $module) {
  617. $function = $module . '_' . $this->entityTypeId . '_storage_load';
  618. $function($entities);
  619. }
  620. }
  621. }
  622. /**
  623. * {@inheritdoc}
  624. */
  625. protected function invokeHook($hook, EntityInterface $entity) {
  626. /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  627. switch ($hook) {
  628. case 'presave':
  629. $this->invokeFieldMethod('preSave', $entity);
  630. break;
  631. case 'insert':
  632. $this->invokeFieldPostSave($entity, FALSE);
  633. break;
  634. case 'update':
  635. $this->invokeFieldPostSave($entity, TRUE);
  636. break;
  637. }
  638. parent::invokeHook($hook, $entity);
  639. }
  640. /**
  641. * Invokes a method on the Field objects within an entity.
  642. *
  643. * Any argument passed will be forwarded to the invoked method.
  644. *
  645. * @param string $method
  646. * The name of the method to be invoked.
  647. * @param \Drupal\Core\Entity\ContentEntityInterface $entity
  648. * The entity object.
  649. *
  650. * @return array
  651. * A multidimensional associative array of results, keyed by entity
  652. * translation language code and field name.
  653. */
  654. protected function invokeFieldMethod($method, ContentEntityInterface $entity) {
  655. $result = [];
  656. $args = array_slice(func_get_args(), 2);
  657. $langcodes = array_keys($entity->getTranslationLanguages());
  658. // Ensure that the field method is invoked as first on the current entity
  659. // translation and then on all other translations.
  660. $current_entity_langcode = $entity->language()->getId();
  661. if (reset($langcodes) != $current_entity_langcode) {
  662. $langcodes = array_diff($langcodes, [$current_entity_langcode]);
  663. array_unshift($langcodes, $current_entity_langcode);
  664. }
  665. foreach ($langcodes as $langcode) {
  666. $translation = $entity->getTranslation($langcode);
  667. // For non translatable fields, there is only one field object instance
  668. // across all translations and it has as parent entity the entity in the
  669. // default entity translation. Therefore field methods on non translatable
  670. // fields should be invoked only on the default entity translation.
  671. $fields = $translation->isDefaultTranslation() ? $translation->getFields() : $translation->getTranslatableFields();
  672. foreach ($fields as $name => $items) {
  673. // call_user_func_array() is way slower than a direct call so we avoid
  674. // using it if have no parameters.
  675. $result[$langcode][$name] = $args ? call_user_func_array([$items, $method], $args) : $items->{$method}();
  676. }
  677. }
  678. // We need to call the delete method for field items of removed
  679. // translations.
  680. if ($method == 'postSave' && !empty($entity->original)) {
  681. $original_langcodes = array_keys($entity->original->getTranslationLanguages());
  682. foreach (array_diff($original_langcodes, $langcodes) as $removed_langcode) {
  683. $translation = $entity->original->getTranslation($removed_langcode);
  684. $fields = $translation->getTranslatableFields();
  685. foreach ($fields as $name => $items) {
  686. $items->delete();
  687. }
  688. }
  689. }
  690. return $result;
  691. }
  692. /**
  693. * Invokes the post save method on the Field objects within an entity.
  694. *
  695. * @param \Drupal\Core\Entity\ContentEntityInterface $entity
  696. * The entity object.
  697. * @param bool $update
  698. * Specifies whether the entity is being updated or created.
  699. */
  700. protected function invokeFieldPostSave(ContentEntityInterface $entity, $update) {
  701. // For each entity translation this returns an array of resave flags keyed
  702. // by field name, thus we merge them to obtain a list of fields to resave.
  703. $resave = [];
  704. foreach ($this->invokeFieldMethod('postSave', $entity, $update) as $translation_results) {
  705. $resave += array_filter($translation_results);
  706. }
  707. if ($resave) {
  708. $this->doSaveFieldItems($entity, array_keys($resave));
  709. }
  710. }
  711. /**
  712. * Checks whether the field values changed compared to the original entity.
  713. *
  714. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
  715. * Field definition of field to compare for changes.
  716. * @param \Drupal\Core\Entity\ContentEntityInterface $entity
  717. * Entity to check for field changes.
  718. * @param \Drupal\Core\Entity\ContentEntityInterface $original
  719. * Original entity to compare against.
  720. *
  721. * @return bool
  722. * True if the field value changed from the original entity.
  723. */
  724. protected function hasFieldValueChanged(FieldDefinitionInterface $field_definition, ContentEntityInterface $entity, ContentEntityInterface $original) {
  725. $field_name = $field_definition->getName();
  726. $langcodes = array_keys($entity->getTranslationLanguages());
  727. if ($langcodes !== array_keys($original->getTranslationLanguages())) {
  728. // If the list of langcodes has changed, we need to save.
  729. return TRUE;
  730. }
  731. foreach ($langcodes as $langcode) {
  732. $items = $entity->getTranslation($langcode)->get($field_name)->filterEmptyItems();
  733. $original_items = $original->getTranslation($langcode)->get($field_name)->filterEmptyItems();
  734. // If the field items are not equal, we need to save.
  735. if (!$items->equals($original_items)) {
  736. return TRUE;
  737. }
  738. }
  739. return FALSE;
  740. }
  741. /**
  742. * Populates the affected flag for all the revision translations.
  743. *
  744. * @param \Drupal\Core\Entity\ContentEntityInterface $entity
  745. * An entity object being saved.
  746. */
  747. protected function populateAffectedRevisionTranslations(ContentEntityInterface $entity) {
  748. if ($this->entityType->isTranslatable() && $this->entityType->isRevisionable()) {
  749. $languages = $entity->getTranslationLanguages();
  750. foreach ($languages as $langcode => $language) {
  751. $translation = $entity->getTranslation($langcode);
  752. $current_affected = $translation->isRevisionTranslationAffected();
  753. if (!isset($current_affected) || ($entity->isNewRevision() && !$translation->isRevisionTranslationAffectedEnforced())) {
  754. // When setting the revision translation affected flag we have to
  755. // explicitly set it to not be enforced. By default it will be
  756. // enforced automatically when being set, which allows us to determine
  757. // if the flag has been already set outside the storage in which case
  758. // we should not recompute it.
  759. // @see \Drupal\Core\Entity\ContentEntityBase::setRevisionTranslationAffected().
  760. $new_affected = $translation->hasTranslationChanges() ? TRUE : NULL;
  761. $translation->setRevisionTranslationAffected($new_affected);
  762. $translation->setRevisionTranslationAffectedEnforced(FALSE);
  763. }
  764. }
  765. }
  766. }
  767. /**
  768. * Ensures integer entity key values are valid.
  769. *
  770. * The identifier sanitization provided by this method has been introduced
  771. * as Drupal used to rely on the database to facilitate this, which worked
  772. * correctly with MySQL but led to errors with other DBMS such as PostgreSQL.
  773. *
  774. * @param array $ids
  775. * The entity key values to verify.
  776. * @param string $entity_key
  777. * (optional) The entity key to sanitise values for. Defaults to 'id'.
  778. *
  779. * @return array
  780. * The sanitized list of entity key values.
  781. */
  782. protected function cleanIds(array $ids, $entity_key = 'id') {
  783. $definitions = $this->entityManager->getBaseFieldDefinitions($this->entityTypeId);
  784. $field_name = $this->entityType->getKey($entity_key);
  785. if ($field_name && $definitions[$field_name]->getType() == 'integer') {
  786. $ids = array_filter($ids, function ($id) {
  787. return is_numeric($id) && $id == (int) $id;
  788. });
  789. $ids = array_map('intval', $ids);
  790. }
  791. return $ids;
  792. }
  793. /**
  794. * Gets entities from the persistent cache backend.
  795. *
  796. * @param array|null &$ids
  797. * If not empty, return entities that match these IDs. IDs that were found
  798. * will be removed from the list.
  799. *
  800. * @return \Drupal\Core\Entity\ContentEntityInterface[]
  801. * Array of entities from the persistent cache.
  802. */
  803. protected function getFromPersistentCache(array &$ids = NULL) {
  804. if (!$this->entityType->isPersistentlyCacheable() || empty($ids)) {
  805. return [];
  806. }
  807. $entities = [];
  808. // Build the list of cache entries to retrieve.
  809. $cid_map = [];
  810. foreach ($ids as $id) {
  811. $cid_map[$id] = $this->buildCacheId($id);
  812. }
  813. $cids = array_values($cid_map);
  814. if ($cache = $this->cacheBackend->getMultiple($cids)) {
  815. // Get the entities that were found in the cache.
  816. foreach ($ids as $index => $id) {
  817. $cid = $cid_map[$id];
  818. if (isset($cache[$cid])) {
  819. $entities[$id] = $cache[$cid]->data;
  820. unset($ids[$index]);
  821. }
  822. }
  823. }
  824. return $entities;
  825. }
  826. /**
  827. * Stores entities in the persistent cache backend.
  828. *
  829. * @param \Drupal\Core\Entity\ContentEntityInterface[] $entities
  830. * Entities to store in the cache.
  831. */
  832. protected function setPersistentCache($entities) {
  833. if (!$this->entityType->isPersistentlyCacheable()) {
  834. return;
  835. }
  836. $cache_tags = [
  837. $this->entityTypeId . '_values',
  838. 'entity_field_info',
  839. ];
  840. foreach ($entities as $id => $entity) {
  841. $this->cacheBackend->set($this->buildCacheId($id), $entity, CacheBackendInterface::CACHE_PERMANENT, $cache_tags);
  842. }
  843. }
  844. /**
  845. * {@inheritdoc}
  846. */
  847. public function loadUnchanged($id) {
  848. $ids = [$id];
  849. // The cache invalidation in the parent has the side effect that loading the
  850. // same entity again during the save process (for example in
  851. // hook_entity_presave()) will load the unchanged entity. Simulate this
  852. // by explicitly removing the entity from the static cache.
  853. parent::resetCache($ids);
  854. // The default implementation in the parent class unsets the current cache
  855. // and then reloads the entity. That is slow, especially if this is done
  856. // repeatedly in the same request, e.g. when validating and then saving
  857. // an entity. Optimize this for content entities by trying to load them
  858. // directly from the persistent cache again, as in contrast to the static
  859. // cache the persistent one will never be changed until the entity is saved.
  860. $entities = $this->getFromPersistentCache($ids);
  861. if (!$entities) {
  862. $entities[$id] = $this->load($id);
  863. }
  864. else {
  865. // As the entities are put into the persistent cache before the post load
  866. // has been executed we have to execute it if we have retrieved the
  867. // entity directly from the persistent cache.
  868. $this->postLoad($entities);
  869. if ($this->entityType->isStaticallyCacheable()) {
  870. // As we've removed the entity from the static cache already we have to
  871. // put the loaded unchanged entity there to simulate the behavior of the
  872. // parent.
  873. $this->setStaticCache($entities);
  874. }
  875. }
  876. return $entities[$id];
  877. }
  878. /**
  879. * {@inheritdoc}
  880. */
  881. public function resetCache(array $ids = NULL) {
  882. if ($ids) {
  883. $cids = [];
  884. foreach ($ids as $id) {
  885. unset($this->entities[$id]);
  886. $cids[] = $this->buildCacheId($id);
  887. }
  888. if ($this->entityType->isPersistentlyCacheable()) {
  889. $this->cacheBackend->deleteMultiple($cids);
  890. }
  891. }
  892. else {
  893. $this->entities = [];
  894. if ($this->entityType->isPersistentlyCacheable()) {
  895. Cache::invalidateTags([$this->entityTypeId . '_values']);
  896. }
  897. }
  898. }
  899. /**
  900. * Builds the cache ID for the passed in entity ID.
  901. *
  902. * @param int $id
  903. * Entity ID for which the cache ID should be built.
  904. *
  905. * @return string
  906. * Cache ID that can be passed to the cache backend.
  907. */
  908. protected function buildCacheId($id) {
  909. return "values:{$this->entityTypeId}:$id";
  910. }
  911. }