<?php
namespace App\EventListener;
use Symfony\Component\HttpKernel\KernelInterface;
use Vich\UploaderBundle\Event\Event;
class MediaEventListener
{
private $appKernel;
public function __construct(KernelInterface $appKernel)
{
$this->appKernel = $appKernel;
}
/**
* 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
* @param Event $event
* @return mixed
* @throws \Exception
*/
public function onVichUploaderPostUpload(Event $event)
{
$mediaPath = $this->appKernel->getProjectDir() . '/public/media';
$object = $event->getObject();
$mapping = $event->getMapping();
$path = $object->getPath();
$mediaType = $object->getMediaType();
// throw new \Exception( ' - mediaType : '. $mediaType . ' - path : ' . $path);
if($mediaType === 'pdf') {
$jpgPath = str_replace('.pdf', '.jpg', $path);
$pdfFullPath = $mediaPath . '/' . $path;
$jpgFullPath = $mediaPath . '/' . $jpgPath;
$output = array();
$return_var = 0;
exec('/usr/bin/gs -dNOPAUSE -dBATCH -sDEVICE=jpeg -r300 -sOutputFile=' . $jpgFullPath . ' ' . $pdfFullPath, $output, $return_var);
$object->setPath($jpgPath);
}
return $event;
}
/**
* Lors de la suppression d'un média, s'il a le type PDF, on supprime également le pdf associé
* @param Event $event
* @return mixed
* @throws \Exception
*/
public function onVichUploaderPreRemove(Event $event)
{
$mediaPath = $this->appKernel->getProjectDir() . '/public/media';
$object = $event->getObject();
$mapping = $event->getMapping();
$path = $object->getPath();
$mediaType = $object->getMediaType();
if($mediaType === 'pdf') {
$pdfPath = str_replace('.jpg', '.pdf', $path);
$pdfFullPath = $mediaPath . '/' . $pdfPath;
// throw new \Exception( ' - mediaType : '. $mediaType . ' - $pdfFullPath : ' . $pdfFullPath);
if(file_exists($pdfFullPath))
@unlink($pdfFullPath);
}
return $event;
}
}