vendor/crehler/image-booster/src/Subscriber/MediaLoadedSubscriber.php line 38

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Crehler\ImageBooster\Subscriber;
  3. use Crehler\ImageBooster\Message\GenerateWatermarkMessage;
  4. use Crehler\ImageBooster\Service\MediaBoosterService;
  5. use Enqueue\MessengerAdapter\EnvelopeItem\TransportConfiguration;
  6. use Shopware\Core\Content\Media\MediaEvents;
  7. use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityDeletedEvent;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\Messenger\MessageBusInterface;
  12. class MediaLoadedSubscriber implements EventSubscriberInterface
  13. {
  14.     private MessageBusInterface $messageBus;
  15.     private MediaBoosterService $mediaBoosterService;
  16.     public function __construct(
  17.         MessageBusInterface $messageBus,
  18.         MediaBoosterService $mediaBoosterService
  19.     )
  20.     {
  21.         $this->messageBus $messageBus;
  22.         $this->mediaBoosterService $mediaBoosterService;
  23.     }
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [
  27.             MediaEvents::MEDIA_DELETED_EVENT => 'onMediaDeleted',
  28.             MediaEvents::MEDIA_WRITTEN_EVENT => 'onMediaWritten'
  29.         ];
  30.     }
  31.     public function onMediaWritten(EntityWrittenEvent $event): void
  32.     {
  33.         if ($event->getContext()->getScope() === "system") return;
  34.         $ids = [];
  35.         /** @var EntityWriteResult $writeResult */
  36.         foreach ($event->getWriteResults() as $writeResult) {
  37.             $key $writeResult->getPrimaryKey();
  38.             $ids[] = $key;
  39.         }
  40.         $message = new GenerateWatermarkMessage();
  41.         $message->setMediaIds($ids);
  42.         $message->setSource("media");
  43.         $this->messageBus->dispatch($message, [new TransportConfiguration(['topic' => 'crehlerimagebooster'])]);
  44.     }
  45.     public function onMediaDeleted(EntityDeletedEvent $event)
  46.     {
  47.         foreach ($event->getIds() as $id) {
  48.             $this->mediaBoosterService->clearBoosters($id);
  49.         }
  50.     }
  51. }