src/EventListener/FileUploadListener.php line 16

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Vich\UploaderBundle\Event\Event;
  4. use Symfony\Component\Filesystem\Filesystem;
  5. class FileUploadListener
  6. {
  7.     private Filesystem $filesystem;
  8.     public function __construct()
  9.     {
  10.         $this->filesystem = new Filesystem();
  11.     }
  12.     public function PreUpload(Event $event): void
  13.     {
  14.         $entity $event->getObject();
  15.         $mapping $event->getMapping();
  16.         // Verifica que la entidad tenga un nombre de archivo existente
  17.         $currentFileName $mapping->getFileName($entity);
  18.         if ($currentFileName) {
  19.             $filePath $mapping->getUploadDestination() . '/' $currentFileName;
  20.             // Si el archivo existe, elimínalo
  21.             if ($this->filesystem->exists($filePath)) {
  22.                 $this->filesystem->remove($filePath);
  23.             }
  24.         }
  25.     }
  26. }