Skip to content

Commit

Permalink
Ability to remove file for ReplacingFile (#1462)
Browse files Browse the repository at this point in the history
  • Loading branch information
iksmail authored Sep 29, 2024
1 parent 4638ca7 commit 8056cd5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
20 changes: 19 additions & 1 deletion src/FileAbstraction/ReplacingFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,34 @@
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
* in cases where it is not possible to construct an `UploadedFile`.
*/
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;
}
}
18 changes: 17 additions & 1 deletion src/Storage/AbstractStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 8056cd5

Please sign in to comment.