diff --git a/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php b/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php index 5eb5c30..ba54f66 100644 --- a/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php +++ b/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php @@ -289,11 +289,39 @@ protected function doSave($id, EntityInterface $entity) { */ protected function doPreSave(EntityInterface $entity) { /** @var \Drupal\Core\Entity\ContentEntityBase $entity */ - // Sync the changes made in the fields array to the internal values array. $entity->updateOriginalValues(); - return parent::doPreSave($entity); + $id = $entity->id(); + + // Track the original ID. + if ($entity->getOriginalId() !== NULL) { + $id = $entity->getOriginalId(); + } + + // Track if this entity exists already. + $id_exists = $this->has($id, $entity); + + // A new entity should not already exist. + if ($id_exists && $entity->isNew()) { + throw new EntityStorageException("'{$this->entityTypeId}' entity with ID '$id' already exists."); + } + + // Load the original entity, if any. + if ($id_exists && !isset($entity->original)) { + $entity->original = $this->loadUnchanged($id); + } + + // Reset the persistent cache if this entity type uses it. + if (!$entity->isNew() && $this->entityType->isPersistentlyCacheable()) { + $this->cacheBackend->delete($this->buildCacheId($entity->id())); + } + + // Allow code to run before saving. + $entity->preSave($this); + $this->invokeHook('presave', $entity); + + return $id; } /** @@ -323,6 +351,18 @@ protected function doDelete($entities) { $this->invokeFieldMethod('delete', $entity); } $this->doDeleteFieldItems($entities); + + // Reset the persistent cache if this entity type uses it. + if ($this->entityType->isPersistentlyCacheable()) { + $cids = []; + foreach ($entities as $entity) { + if (!$entity->isNew()) { + $cids[] = $this->buildCacheId($entity->id()); + } + } + + $this->cacheBackend->deleteMultiple($cids); + } } /** @@ -612,20 +652,12 @@ protected function setPersistentCache($entities) { */ public function resetCache(array $ids = NULL) { if ($ids) { - $cids = array(); foreach ($ids as $id) { unset($this->entities[$id]); - $cids[] = $this->buildCacheId($id); - } - if ($this->entityType->isPersistentlyCacheable()) { - $this->cacheBackend->deleteMultiple($cids); } } else { $this->entities = array(); - if ($this->entityType->isPersistentlyCacheable()) { - Cache::invalidateTags(array($this->entityTypeId . '_values')); - } } }