src/EventListener/WebPConversionSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: zeidoun
  5.  * Date: 15/01/2020
  6.  * Time: 13:08
  7.  */
  8. namespace App\EventListener;
  9. use App\Services\UploadedFileToWebPConverter;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpKernel\Event\RequestEvent;
  12. use Symfony\Component\HttpKernel\KernelEvents;
  13. use Symfony\Component\HttpFoundation\File\UploadedFile;
  14. use Symfony\Component\HttpFoundation\File\File;
  15. use Symfony\Component\HttpFoundation\FileBag;
  16. class WebPConversionSubscriber implements EventSubscriberInterface
  17. {
  18.     private  $converter;
  19.     public function __construct(UploadedFileToWebPConverter $converter)
  20.     {
  21.         $this->converter $converter;
  22.     }
  23.     public function onKernelRequest(RequestEvent $event): void
  24.     {
  25.         $request $event->getRequest();
  26.         $files $request->files->all();
  27.         $converted $this->convertFilesToWebP($files);
  28.         $request->files = new FileBag($converted);
  29.     }
  30.     private function convertFilesToWebP(array $files): array
  31.     {
  32.         $result = [];
  33.         foreach ($files as $key => $file) {
  34.             if (is_array($file)) {
  35.                 // Recurse through nested files (e.g. forms with subtypes)
  36.                 $result[$key] = $this->convertFilesToWebP($file);
  37.             } elseif ($file instanceof UploadedFile) {
  38.                 // Convert image and replace with new UploadedFile
  39.                 $webpPath $this->converter->convertToWebP($file);
  40.                 if ($webpPath && file_exists($webpPath)) {
  41.                     $webpFile = new UploadedFile(
  42.                         $webpPath,
  43.                         pathinfo($webpPathPATHINFO_BASENAME),
  44.                         'image/webp',
  45.                         null,
  46.                         true // already moved
  47.                     );
  48.                     $result[$key] = $webpFile;
  49.                 } else {
  50.                     $result[$key] = $file;
  51.                 }
  52.             } else {
  53.                 $result[$key] = $file;
  54.             }
  55.         }
  56.         return $result;
  57.     }
  58.     public static function getSubscribedEvents(): array
  59.     {
  60.         return [
  61.             KernelEvents::REQUEST => ['onKernelRequest'10], // Avant le contrôleur
  62.         ];
  63.     }
  64. }