src/EventSubscriber/CommentSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Order;
  4. use App\Entity\Step;
  5. use App\Entity\User;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  11. use Symfony\Component\Security\Core\User\UserInterface;
  12. use Twig\Environment;
  13. class CommentSubscriber implements EventSubscriberInterface
  14. {
  15.     private Environment $twig;
  16.     private EntityManagerInterface $em;
  17.     private TokenStorageInterface $tokenStorage;
  18.     public function __construct(Environment $twigEntityManagerInterface $emTokenStorageInterface $tokenStorage)
  19.     {
  20.         $this->twig $twig;
  21.         $this->em $em;
  22.         $this->tokenStorage $tokenStorage;
  23.     }
  24.     public function onKernelRequest(RequestEvent $event)
  25.     {
  26.         if (!$event->isMainRequest()) {
  27.             return false;
  28.         }
  29.         $token $this->tokenStorage->getToken();
  30.         if ($token === null) {
  31.             return false;
  32.         }
  33.         /** @var User $user */
  34.         $user $token->getUser();
  35.         if ($user instanceof UserInterface and $user->isContributor()) {
  36.             /** @var Order[] $orders */
  37.             $orders $this->em->getRepository(Order::class)->findWaitingContribution($user);
  38.             $commentsNotRead = [];
  39.             foreach ($orders as $order) {
  40.                 if ($order->getCreation() and $order->getCurrentStep() and $order->getCurrentStep()->getStep()->getConstName() == Step::MAKING) {
  41.                     foreach ($order->getCreation()->getCreationComments() as $creationComment) {
  42.                         if (!$user->getCommentsRead()->contains($creationComment)) {
  43.                             $commentsNotRead[$creationComment->getCreatedAt()->format('YmdHis')] = [
  44.                                 'order' => $order,
  45.                                 'comment' => $creationComment,
  46.                             ];
  47.                         }
  48.                     }
  49.                 }
  50.             }
  51.             rsort($commentsNotRead);
  52.             $this->twig->addGlobal('comments_not_read'$commentsNotRead);
  53.         }
  54.     }
  55.     public static function getSubscribedEvents(): array
  56.     {
  57.         return array(
  58.             KernelEvents::REQUEST => 'onKernelRequest',
  59.         );
  60.     }
  61. }