<?php declare(strict_types=1);
namespace App\Doctrine\Listener;
use App\Contract\Content\DownloadableContentBid;
use App\Entity\DealBid;
use App\Entity\Message\MessageBid;
use App\Entity\ProjectBid;
use App\Entity\ShopVideoBid;
use App\RabbitMq\Handler\DownloadableContentBidHandler;
use App\RabbitMq\TasksPool;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\Event\PostLoadEventArgs;
use Doctrine\ORM\Event\PostPersistEventArgs;
use Doctrine\ORM\Event\PostUpdateEventArgs;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class DownloadableContentBidListener implements EventSubscriberInterface
{
private TasksPool $tasksPool;
private bool $dirty = false;
public function __construct(TasksPool $tasksPool)
{
$this->tasksPool = $tasksPool;
}
/**
* @param DealBid|ProjectBid|ShopVideoBid|MessageBid $contentBid
*/
public function postLoad(DownloadableContentBid $contentBid, PostLoadEventArgs $args): void
{
$contentBid->setWasAccessible($contentBid->isStillAccessible() && $contentBid->getContent()->isContentAccessible());
}
/**
* @param DealBid|ProjectBid|ShopVideoBid|MessageBid $contentBid
*/
public function postPersist(DownloadableContentBid $contentBid, PostPersistEventArgs $args): void
{
$contentBid->setWasAccessible($contentBid->isStillAccessible() && $contentBid->getContent()->isContentAccessible());
if (null === $contentBid->getId() || false === $contentBid->isStillAccessible()) {
return;
}
if (!$contentBid->getContent()->isContentAccessible()) {
return;
}
$this->dirty = true;
$this->tasksPool->addTask(
DownloadableContentBidHandler::class,
'handle',
ClassUtils::getClass($contentBid),
$contentBid->getId(),
[DownloadableContentBidHandler::ADD]
);
}
/**
* @param DealBid|ProjectBid|ShopVideoBid|MessageBid $contentBid
*/
public function postUpdate(DownloadableContentBid $contentBid, PostUpdateEventArgs $args): void
{
// do not process new or unchanged content.
if (null === $contentBid->getId() || false === $contentBid->wasAccessible() || $contentBid->wasAccessible() === $contentBid->isStillAccessible()) {
return;
}
if (!$contentBid->getContent()->isContentAccessible()) {
return;
}
$this->dirty = true;
$this->tasksPool->addTask(
DownloadableContentBidHandler::class,
'handle',
ClassUtils::getClass($contentBid),
$contentBid->getId(),
[DownloadableContentBidHandler::REMOVE]
);
}
public function sendPool(): void
{
if (!$this->dirty) {
return;
}
$this->tasksPool->send();
}
/**
* @return array<string, array<int|string, array<int|string, int|string>|int|string>|string>
*/
public static function getSubscribedEvents(): array
{
$events = [];
if (class_exists(KernelEvents::class)) {
$events[KernelEvents::TERMINATE] = 'sendPool';
}
if (class_exists(ConsoleEvents::class)) {
$events[ConsoleEvents::TERMINATE] = 'sendPool';
}
return $events;
}
}