<?php declare(strict_types=1);
namespace Crehler\ImageBooster\Subscriber;
use Crehler\ImageBooster\Message\GenerateWatermarkMessage;
use Crehler\ImageBooster\Service\MediaBoosterService;
use Enqueue\MessengerAdapter\EnvelopeItem\TransportConfiguration;
use Shopware\Core\Content\Media\MediaEvents;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityDeletedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\MessageBusInterface;
class MediaLoadedSubscriber implements EventSubscriberInterface
{
private MessageBusInterface $messageBus;
private MediaBoosterService $mediaBoosterService;
public function __construct(
MessageBusInterface $messageBus,
MediaBoosterService $mediaBoosterService
)
{
$this->messageBus = $messageBus;
$this->mediaBoosterService = $mediaBoosterService;
}
public static function getSubscribedEvents(): array
{
return [
MediaEvents::MEDIA_DELETED_EVENT => 'onMediaDeleted',
MediaEvents::MEDIA_WRITTEN_EVENT => 'onMediaWritten'
];
}
public function onMediaWritten(EntityWrittenEvent $event): void
{
if ($event->getContext()->getScope() === "system") return;
$ids = [];
/** @var EntityWriteResult $writeResult */
foreach ($event->getWriteResults() as $writeResult) {
$key = $writeResult->getPrimaryKey();
$ids[] = $key;
}
$message = new GenerateWatermarkMessage();
$message->setMediaIds($ids);
$message->setSource("media");
$this->messageBus->dispatch($message, [new TransportConfiguration(['topic' => 'crehlerimagebooster'])]);
}
public function onMediaDeleted(EntityDeletedEvent $event)
{
foreach ($event->getIds() as $id) {
$this->mediaBoosterService->clearBoosters($id);
}
}
}