<?php
namespace App\EventListener;
use Vich\UploaderBundle\Event\Event;
use Symfony\Component\Filesystem\Filesystem;
class FileUploadListener
{
private Filesystem $filesystem;
public function __construct()
{
$this->filesystem = new Filesystem();
}
public function PreUpload(Event $event): void
{
$entity = $event->getObject();
$mapping = $event->getMapping();
// Verifica que la entidad tenga un nombre de archivo existente
$currentFileName = $mapping->getFileName($entity);
if ($currentFileName) {
$filePath = $mapping->getUploadDestination() . '/' . $currentFileName;
// Si el archivo existe, elimÃnalo
if ($this->filesystem->exists($filePath)) {
$this->filesystem->remove($filePath);
}
}
}
}