From 8056cd5561507ccf599500449cb95970ffb41ca7 Mon Sep 17 00:00:00 2001 From: iksmail Date: Sun, 29 Sep 2024 17:10:27 +0300 Subject: [PATCH] Ability to remove file for ReplacingFile (#1462) --- src/FileAbstraction/ReplacingFile.php | 20 +++++++++++++++++++- src/Storage/AbstractStorage.php | 18 +++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/FileAbstraction/ReplacingFile.php b/src/FileAbstraction/ReplacingFile.php index cc3cf22d..34ca4456 100644 --- a/src/FileAbstraction/ReplacingFile.php +++ b/src/FileAbstraction/ReplacingFile.php @@ -5,7 +5,6 @@ namespace Vich\UploaderBundle\FileAbstraction; use Symfony\Component\HttpFoundation\File\File; -use Symfony\Component\HttpFoundation\File\UploadedFile; /** * This class can be used to signal that the given file should be "uploaded" into the Vich-abstraction @@ -13,8 +12,27 @@ */ class ReplacingFile extends File { + public function __construct( + string $path, + bool $checkPath = true, + private readonly bool $removeReplacedFile = false, + private readonly bool $removeReplacedFileOnError = false + ) { + parent::__construct($path, $checkPath); + } + public function getClientOriginalName(): string { return $this->getFilename(); } + + public function isRemoveReplacedFile(): bool + { + return $this->removeReplacedFile; + } + + public function isRemoveReplacedFileOnError(): bool + { + return $this->removeReplacedFileOnError; + } } diff --git a/src/Storage/AbstractStorage.php b/src/Storage/AbstractStorage.php index e66afaf1..94c66b40 100644 --- a/src/Storage/AbstractStorage.php +++ b/src/Storage/AbstractStorage.php @@ -46,7 +46,23 @@ public function upload(object $obj, PropertyMapping $mapping): void $dir = $mapping->getUploadDir($obj); - $this->doUpload($mapping, $file, $dir, $name); + try { + $this->doUpload($mapping, $file, $dir, $name); + } catch (\Exception $e) { + if ($file instanceof ReplacingFile + && $file->isRemoveReplacedFileOnError() + ) { + unlink($file->getPathname()); + } + + throw $e; + } + + if ($file instanceof ReplacingFile + && $file->isRemoveReplacedFile() + ) { + unlink($file->getPathname()); + } } abstract protected function doRemove(PropertyMapping $mapping, ?string $dir, string $name): ?bool;