<?php
namespace App\EventListener;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\MediaObject;
use App\Entity\Resize;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Intervention\Image\ImageManager;
use Symfony\Component\HttpKernel\KernelInterface;
use App\Service\ImageResize;
class MediaObjectCreatedListener implements EventSubscriberInterface
{
private EntityManagerInterface $entityManager;
private $kernel;
private $imageResize;
public function __construct(EntityManagerInterface $entityManager, KernelInterface $kernel, ImageResize $imageResize)
{
$this->entityManager = $entityManager;
$this->kernel = $kernel;
$this->imageResize = $imageResize;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['saveMediaObject', EventPriorities::POST_WRITE],
];
}
public function saveMediaObject(ViewEvent $event)
{
$mainMedia = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$mainMedia instanceof MediaObject) {
return;
}
// echo $mainMedia->getId();
// echo $mainMedia->filePath;
$year = date('Y');
$month = date('m');
$documentRoot = $this->kernel->getProjectDir() . '/public/media';
$path = $documentRoot . "/$year/$month/";
$name = $mainMedia->filePath;
$uri = $path . $name;
if ($this->isImage($uri)) {
$sizes = [90, 230, 700];
$manager = new ImageManager(
new \Intervention\Image\Drivers\Gd\Driver()
);
foreach($sizes as $s){
$image = $manager->read($uri);
$image->scale(width: $s);
$newName = "{$s}_px_" . $name;
$image->save($path . $newName );
$newMedia = new MediaObject();
$newMedia->filePath = $newName;
$newMedia->setName("resize-$s");
$newMedia->setSize($s);
$newMedia->setResizeImgParent($mainMedia);
$this->entityManager->persist($newMedia);
$this->entityManager->flush();
}
}
// die;
}
private function isImage($file)
{
$allowedTypes = [
IMAGETYPE_GIF,
IMAGETYPE_JPEG,
IMAGETYPE_PNG,
IMAGETYPE_WEBP,
// Add more as needed
];
$imageInfo = @getimagesize($file);
if ($imageInfo && in_array($imageInfo[2], $allowedTypes)) {
return true;
}
return false;
}
}