- <?php
- /**
-  * Created by PhpStorm.
-  * User: zeidoun
-  * Date: 15/01/2020
-  * Time: 13:08
-  */
- namespace App\EventListener;
- use App\Services\UploadedFileToWebPConverter;
- use Symfony\Component\EventDispatcher\EventSubscriberInterface;
- use Symfony\Component\HttpKernel\Event\RequestEvent;
- use Symfony\Component\HttpKernel\KernelEvents;
- use Symfony\Component\HttpFoundation\File\UploadedFile;
- use Symfony\Component\HttpFoundation\File\File;
- use Symfony\Component\HttpFoundation\FileBag;
- class WebPConversionSubscriber implements EventSubscriberInterface
- {
-     private  $converter;
-     public function __construct(UploadedFileToWebPConverter $converter)
-     {
-         $this->converter = $converter;
-     }
-     public function onKernelRequest(RequestEvent $event): void
-     {
-         $request = $event->getRequest();
-         $files = $request->files->all();
-         $converted = $this->convertFilesToWebP($files);
-         $request->files = new FileBag($converted);
-     }
-     private function convertFilesToWebP(array $files): array
-     {
-         $result = [];
-         foreach ($files as $key => $file) {
-             if (is_array($file)) {
-                 // Recurse through nested files (e.g. forms with subtypes)
-                 $result[$key] = $this->convertFilesToWebP($file);
-             } elseif ($file instanceof UploadedFile) {
-                 if($key == 'fileDesignPhoto'){
-                     $result[$key] = $file;
-                 }else {
-                     // Convert image and replace with new UploadedFile
-                     $webpPath = $this->converter->convertToWebP($file);
-                     if ($webpPath && file_exists($webpPath)) {
-                         $webpFile = new UploadedFile(
-                             $webpPath,
-                             pathinfo($webpPath, PATHINFO_BASENAME),
-                             'image/webp',
-                             null,
-                             true // already moved
-                         );
-                         $result[$key] = $webpFile;
-                     } else {
-                         $result[$key] = $file;
-                     }
-                 }
-             } else {
-                 $result[$key] = $file;
-             }
-         }
-         return $result;
-     }
-     public static function getSubscribedEvents(): array
-     {
-         return [
-             KernelEvents::REQUEST => ['onKernelRequest', 10], // Avant le contrôleur
-         ];
-     }
- }
-