<?php
namespace App\EventSubscriber;
use Twig\Environment;
use App\Utils\NotificationMenu;
use App\Repository\NotificationRepository;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Notification;
class NotificationSubcriber implements EventSubscriberInterface
{
const MENUURL=['app_order_detail','app_ticket_details'];
private $twig;
private $notificationRepository;
private $notificationMenu;
private $entityManager;
public function __construct(Environment $twig,
NotificationRepository $notificationRepository,
NotificationMenu $notificationMenu,
ManagerRegistry $doctrine
)
{
$this->twig=$twig;
$this->notificationRepository=$notificationRepository;
$this->notificationMenu=$notificationMenu;
$this->entityManager = $doctrine->getManager();
}
public static function getSubscribedEvents()
{
// return the subscribed events, their methods and priorities
return [
KernelEvents::REQUEST => [
['notifyRequest', 0],
],
];
}
public function notifyRequest(RequestEvent $event)
{
$route=$event->getRequest()->attributes->get('_route');
if (in_array($route, SELF::MENUURL)) {
$id=$event->getRequest()->attributes->get('notif');
$notifObject=null;
if(!is_null($id)){
$notifObject=$this->notificationRepository->find($id);
}
if($notifObject instanceof Notification){
$notifObject->setStatus(1);
$this->entityManager->persist($notifObject);
$this->entityManager->flush();
}
}
$notifs=$this->notificationRepository->findBy(['direction'=>'agent'],['createdAt'=>'DESC'],6);
$notifCount=count($this->notificationRepository->findBy(['direction'=>'agent','status'=>0]));
$menu=$this->notificationMenu->buildNotifMenu($notifs);
$this->twig->addGlobal('menu',$menu);
$this->twig->addGlobal('notifCount',$notifCount);
}
}