ContentEntityStorageBase.php 41 KB

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