<?php declare(strict_types=1);
namespace Crehler\ImageBooster\Subscriber;
use Crehler\ImageBooster\Enum\MediaBoosterTypeEnum;
use Crehler\ImageBooster\Event\WatermarkImageGeneratedEvent;
use Crehler\ImageBooster\Exception\WatermarkAdditionalExtensionException;
use Crehler\ImageBooster\Service\Generator\CavifGenerator;
use Crehler\ImageBooster\Service\Generator\PhpGenerator;
use Crehler\ImageBooster\Service\Generator\WebPGeneratorInterface;
use Crehler\ImageBooster\Service\ImageFileSystemSaver;
use Crehler\ImageBooster\Service\MediaBoosterService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class WatermarkEventsSubscriber implements EventSubscriberInterface
{
private PhpGenerator $webpGenerator;
private ImageFileSystemSaver $fileSystemSaver;
private MediaBoosterService $mediaBoosterService;
private CavifGenerator $cavifGenerator;
const TARGET_QUALITY = 65;
public function __construct(
PhpGenerator $webPGenerator,
CavifGenerator $cavifGenerator,
ImageFileSystemSaver $fileSystemSaver,
MediaBoosterService $mediaBoosterService
)
{
$this->webpGenerator = $webPGenerator;
$this->cavifGenerator = $cavifGenerator;
$this->fileSystemSaver = $fileSystemSaver;
$this->mediaBoosterService = $mediaBoosterService;
}
public static function getSubscribedEvents(): array
{
return [
WatermarkImageGeneratedEvent::class => [['generateWebp', 1], ['generateAvif', 2]]
];
}
public function generateWebp(WatermarkImageGeneratedEvent $event): void
{
$width = imagesx($event->getImage());
$height = imagesx($event->getImage());
$content = $this->webpGenerator->generate($event->getImage(), self::TARGET_QUALITY);
$imageData = $this->fileSystemSaver->saveImageToPath($content, $event->getPath(), 'webp', $width, $height);
if (!$imageData) {
throw new WatermarkAdditionalExtensionException();
}
$this->mediaBoosterService->addWatermarkRecord(
$event->getMediaEntity(),
($event->getType() === WatermarkImageGeneratedEvent::TYPE_MAIN)?
MediaBoosterTypeEnum::WATERMARK_TYPE_WEBP:MediaBoosterTypeEnum::WATERMARK_TYPE_WEBP_THUMB,
$imageData
);
}
public function generateAvif(WatermarkImageGeneratedEvent $event): void
{
$width = imagesx($event->getImage());
$height = imagesx($event->getImage());
$path = sprintf("%s.%s", $event->getPath(), $event->getMediaEntity()->getFileExtension());
$resultPath = $this->cavifGenerator->generateAvif($path, $event->getPath(), self::TARGET_QUALITY);
$imageData = $this->fileSystemSaver->saveImageToPath(null, $event->getPath(), 'avif', $width, $height, $resultPath);
if (!$imageData) {
throw new WatermarkAdditionalExtensionException();
}
$this->mediaBoosterService->addWatermarkRecord(
$event->getMediaEntity(),
($event->getType() === WatermarkImageGeneratedEvent::TYPE_MAIN)?
MediaBoosterTypeEnum::WATERMARK_TYPE_AVIF:MediaBoosterTypeEnum::WATERMARK_TYPE_AVIF_THUMB,
$imageData
);
}
}