<?php declare(strict_types=1);
namespace App\Doctrine\Listener;
use App\Contract\Content\DownloadableContent;
use App\Entity\Deal;
use App\Entity\Message\MessageReception;
use App\Entity\Project;
use App\Entity\ShopVideo;
use App\RabbitMq\Handler\DownloadableContentHandler;
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 DownloadableContentListener implements EventSubscriberInterface
{
private TasksPool $tasksPool;
private bool $dirty = false;
public function __construct(TasksPool $tasksPool)
{
$this->tasksPool = $tasksPool;
}
/**
* @param Deal|Project|ShopVideo|MessageReception $content
*/
public function postLoad(DownloadableContent $content, PostLoadEventArgs $args): void
{
$content->setWasAccessible($content->isContentAccessible());
}
/**
* @param Deal|Project|ShopVideo|MessageReception $content
*/
public function postPersist(DownloadableContent $content, PostPersistEventArgs $args): void
{
$content->setWasAccessible($content->isContentAccessible());
}
/**
* @param Deal|Project|ShopVideo|MessageReception $content
*/
public function postUpdate(DownloadableContent $content, PostUpdateEventArgs $args): void
{
// do not process new or unchanged content.
if (null === $content->getId() || $content->wasAccessible() === $content->isContentAccessible()) {
return;
}
$this->dirty = true;
if (!$content->isContentAccessible()) {
$this->tasksPool->addTask(
DownloadableContentHandler::class,
'handle',
ClassUtils::getClass($content),
$content->getId(),
[DownloadableContentHandler::REMOVE]
);
return;
}
$this->tasksPool->addTask(
DownloadableContentHandler::class,
'handle',
ClassUtils::getClass($content),
$content->getId(),
[DownloadableContentHandler::ADD]
);
}
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;
}
}