From a9020a5b935788b515f289a79155ea9d6c0b818a Mon Sep 17 00:00:00 2001 From: Maurice Wijnia Date: Tue, 18 Nov 2025 15:34:14 +0100 Subject: [PATCH] feat: add file replacement functionality in AttachmentManager --- src/AttachmentManager.php | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/AttachmentManager.php b/src/AttachmentManager.php index 1e7df06..5ddceb4 100644 --- a/src/AttachmentManager.php +++ b/src/AttachmentManager.php @@ -181,6 +181,39 @@ public function upload(UploadedFile $file, ?string $desiredPath = null): Attachm ]); } + /** + * Replace existing file on disk and update database entry. + * + * @throws DestinationAlreadyExistsException + * @throws DisallowedCharacterException + */ + public function replace(UploadedFile $file, Attachment $attachment): Attachment + { + $filename = new Filename($file); + + $this->validateBasename($filename); + + $disk = $this->getFilesystem(); + + $path = implode('/', array_filter([$attachment->path, $filename])); + + if ($disk->exists($path) && $path !== $attachment->full_path) { + throw new DestinationAlreadyExistsException(); + } + + $disk->delete($attachment->full_path); + $disk->put($path, $file->getContent()); + + $attachment->update([ + 'name' => $filename->name, + 'extension' => $filename->extension, + 'mime_type' => $file->getMimeType(), + 'size' => $file->getSize(), + ]); + + return $attachment; + } + /** * Validate filename and throw exception if validation fails. * @@ -222,7 +255,7 @@ public function rename(Attachment $file, string $name): void * * @throws DestinationAlreadyExistsException if conflicting file exists in desired path. */ - public function move(Attachment $file, string $desiredPath): void + public function move(Attachment $file, ?string $desiredPath): void { $disk = $this->getFilesystem(); $path = "{$desiredPath}/{$file->filename}";