src/EventListener/MediaEventListener.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpKernel\KernelInterface;
  4. use Vich\UploaderBundle\Event\Event;
  5. class MediaEventListener
  6. {
  7.     private $appKernel;
  8.     public function __construct(KernelInterface $appKernel)
  9.     {
  10.         $this->appKernel $appKernel;
  11.     }
  12.     /**
  13.      * après l'uplad d'une image, si c'est un PDF, on le convertit en jpg, on substitue le fichier PDF par le jpg mais on garde le PDF afin de pouvoir l'utiliser par la suite
  14.      * @param Event $event
  15.      * @return mixed
  16.      * @throws \Exception
  17.      */
  18.     public function onVichUploaderPostUpload(Event $event)
  19.     {
  20.         $mediaPath $this->appKernel->getProjectDir() . '/public/media';
  21.         $object $event->getObject();
  22.         $mapping $event->getMapping();
  23.         $path $object->getPath();
  24.         $mediaType $object->getMediaType();
  25.         // throw new \Exception( ' - mediaType : '. $mediaType . ' - path : ' . $path);
  26.         if($mediaType === 'pdf') {
  27.             $jpgPath str_replace('.pdf''.jpg'$path);
  28.             $pdfFullPath $mediaPath '/' $path;
  29.             $jpgFullPath $mediaPath '/' $jpgPath;
  30.             $output = array();
  31.             $return_var 0;
  32.             exec('/usr/bin/gs -dNOPAUSE -dBATCH -sDEVICE=jpeg -r300 -sOutputFile=' $jpgFullPath ' ' $pdfFullPath$output$return_var);
  33.             $object->setPath($jpgPath);
  34.         }
  35.         return $event;
  36.     }
  37.     /**
  38.      * Lors de la suppression d'un média, s'il a le type PDF, on supprime également le pdf  associé
  39.      * @param Event $event
  40.      * @return mixed
  41.      * @throws \Exception
  42.      */
  43.     public function onVichUploaderPreRemove(Event $event)
  44.     {
  45.         $mediaPath $this->appKernel->getProjectDir() . '/public/media';
  46.         $object $event->getObject();
  47.         $mapping $event->getMapping();
  48.         $path $object->getPath();
  49.         $mediaType $object->getMediaType();
  50.         if($mediaType === 'pdf') {
  51.             $pdfPath str_replace('.jpg''.pdf'$path);
  52.             $pdfFullPath $mediaPath '/' $pdfPath;
  53.             // throw new \Exception( ' - mediaType : '. $mediaType . ' - $pdfFullPath : ' . $pdfFullPath);
  54.             if(file_exists($pdfFullPath))
  55.                 @unlink($pdfFullPath);
  56.         }
  57.         return $event;
  58.     }
  59. }