From c0b4172f22acfe3d9b2cdf0781f8c98eaebcffe0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20B=C3=B6hmer?= Date: Wed, 13 May 2020 20:46:13 +0200 Subject: [PATCH] Ensure that attachments are not used in preview when deleting, so we do not encounter integrity violations. This fixes issue #50. --- .../AttachmentContainingDBElement.php | 5 +++++ .../AttachmentDeleteListener.php | 20 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/Entity/Attachments/AttachmentContainingDBElement.php b/src/Entity/Attachments/AttachmentContainingDBElement.php index 87ca49f4..3fce528b 100644 --- a/src/Entity/Attachments/AttachmentContainingDBElement.php +++ b/src/Entity/Attachments/AttachmentContainingDBElement.php @@ -111,6 +111,11 @@ abstract class AttachmentContainingDBElement extends AbstractNamedDBElement impl { $this->attachments->removeElement($attachment); + //Check if this is the master attachment -> remove it from master attachment too, or it can not be deleted from DB... + if ($attachment === $this->getMasterPictureAttachment()) { + $this->setMasterPictureAttachment(null); + } + return $this; } } diff --git a/src/EntityListeners/AttachmentDeleteListener.php b/src/EntityListeners/AttachmentDeleteListener.php index 5b09667f..ab033e7e 100644 --- a/src/EntityListeners/AttachmentDeleteListener.php +++ b/src/EntityListeners/AttachmentDeleteListener.php @@ -48,6 +48,7 @@ use App\Services\Attachments\AttachmentPathResolver; use App\Services\Attachments\AttachmentReverseSearch; use Doctrine\ORM\Event\LifecycleEventArgs; use Doctrine\ORM\Event\PreUpdateEventArgs; +use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping\PostRemove; use Doctrine\ORM\Mapping\PreUpdate; use SplFileInfo; @@ -96,6 +97,25 @@ class AttachmentDeleteListener } } + /** + * Ensure that attachments are not used in preview, so that they can be deleted (without integrity violation). + * @ORM\PreRemove() + */ + public function preRemoveHandler(Attachment $attachment, LifecycleEventArgs $event): void + { + //Ensure that the attachment that will be deleted, is not used as preview picture anymore... + $attachment_holder = $attachment->getElement(); + + if ($attachment_holder === null) { + return; + } + + //... Otherwise remove it as preview picture + if ($attachment_holder->getMasterPictureAttachment() === $attachment) { + $attachment_holder->setMasterPictureAttachment(null); + } + } + /** * Removes the file associated with the attachment, after the attachment was deleted. *