<?php
namespace ERP\MediaBundle\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use ERP\MediaBundle\Entity\MediaObject;
use ERP\MediaBundle\Util\Image;
use Intervention\Image\ImageManager;
use Spatie\ImageOptimizer\OptimizerChainFactory;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Vich\UploaderBundle\Storage\StorageInterface;
class MediaObjectCreatedSubscriber implements EventSubscriberInterface
{
/**
* @var ImageManager
*/
private $imageManager;
/**
* @var StorageInterface
*/
private $storage;
/**
* @var \ERP\MediaBundle\Services\Image
*/
private $imageHelper;
public function __construct(
StorageInterface $storage,
\ERP\MediaBundle\Services\Image $imageHelper
) {
$this->storage = $storage;
$this->imageManager = new ImageManager();
$this->imageHelper = $imageHelper;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['mediaObjectCreated', EventPriorities::POST_WRITE],
];
}
public function mediaObjectCreated(RequestEvent $event)
{
$request = $event->getRequest();
if ('api_media_objects_post_collection' !== $request->get('_route')) {
return;
}
/** @var MediaObject $mediaObject */
$mediaObject = $event->getControllerResult();
if (!$mediaObject instanceof MediaObject) {
return;
}
if (!in_array($mediaObject->file->getMimeType(), Image::IMAGE_MIME_TYPES)) {
return;
}
$optimizerChain = OptimizerChainFactory::create();
$originalImagePath = $this->storage->resolvePath($mediaObject, 'file');
$originalImage = $this->imageManager->make($originalImagePath);
$quality = $mediaObject->getOptions()['quality'] ?? \ERP\MediaBundle\Services\Image::QUALITY;
$originalImage->save(null, $quality);
$optimizerChain->optimize($originalImagePath);
$modifiedImagePath = $this->storage->resolvePath($mediaObject, 'fileModified');
if (null === $mediaObject->getParent() && $modifiedImagePath) {
$this->imageHelper->createCommonSizes($modifiedImagePath, $mediaObject);
} elseif ((null === $mediaObject->getParent()) && $originalImagePath) {
$this->imageHelper->createCommonSizes($originalImagePath, $mediaObject);
}
if ($modifiedImagePath) {
$optimizerChain->optimize($modifiedImagePath);
}
}
}