<?php
namespace App\EventSubscriber;
use App\Messenger\DeDuplicationUniqueHashStamp;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerMessageHandledEvent;
class MessengerDeDuplicationSubscriber implements EventSubscriberInterface
{
private CacheItemPoolInterface $cacheItemPool;
public static function getSubscribedEvents(): array
{
return [
WorkerMessageHandledEvent::class => 'handleWorkerMessageHandled',
];
}
public function __construct(CacheItemPoolInterface $cacheItemPool)
{
$this->cacheItemPool = $cacheItemPool;
}
/**
* @throws InvalidArgumentException
*/
public function handleWorkerMessageHandled(WorkerMessageHandledEvent $event): void
{
/** @var DeDuplicationUniqueHashStamp $deDuplicationStamp */
$deDuplicationStamp = $event->getEnvelope()->last(DeDuplicationUniqueHashStamp::class);
if ($deDuplicationStamp instanceof DeDuplicationUniqueHashStamp && $uniqueKey = $deDuplicationStamp->getUniqueKey()) {
$this->cacheItemPool->deleteItem($uniqueKey);
}
}
}