<?php
namespace App\EventSubscriber;
use App\Entity\Order;
use App\Entity\Step;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Twig\Environment;
class CommentSubscriber implements EventSubscriberInterface
{
private Environment $twig;
private EntityManagerInterface $em;
private TokenStorageInterface $tokenStorage;
public function __construct(Environment $twig, EntityManagerInterface $em, TokenStorageInterface $tokenStorage)
{
$this->twig = $twig;
$this->em = $em;
$this->tokenStorage = $tokenStorage;
}
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMainRequest()) {
return false;
}
$token = $this->tokenStorage->getToken();
if ($token === null) {
return false;
}
/** @var User $user */
$user = $token->getUser();
if ($user instanceof UserInterface and $user->isContributor()) {
/** @var Order[] $orders */
$orders = $this->em->getRepository(Order::class)->findWaitingContribution($user);
$commentsNotRead = [];
foreach ($orders as $order) {
if ($order->getCreation() and $order->getCurrentStep() and $order->getCurrentStep()->getStep()->getConstName() == Step::MAKING) {
foreach ($order->getCreation()->getCreationComments() as $creationComment) {
if (!$user->getCommentsRead()->contains($creationComment)) {
$commentsNotRead[$creationComment->getCreatedAt()->format('YmdHis')] = [
'order' => $order,
'comment' => $creationComment,
];
}
}
}
}
rsort($commentsNotRead);
$this->twig->addGlobal('comments_not_read', $commentsNotRead);
}
}
public static function getSubscribedEvents(): array
{
return array(
KernelEvents::REQUEST => 'onKernelRequest',
);
}
}