<?php
namespace App\Listener;
use App\Controller\MessengerController;
use App\Entity\Messaging\Message;
use App\Entity\Messaging\Request;
use App\Entity\User;
use App\Service\Mailer;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
class MessagingListener implements EventSubscriberInterface
{
/**
* @var TokenStorageInterface
*/
private $storage;
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var Mailer
*/
private $mailer;
public function __construct(TokenStorageInterface $storage, EntityManagerInterface $em, Mailer $mailer)
{
$this->storage = $storage;
$this->em = $em;
$this->mailer = $mailer;
}
public function getSubscribedEvents()
{
return [Events::prePersist];
}
private function setLatestMessage(Message $message)
{
$message->getRequest()->setLatest($message);
$md = $this->em->getClassMetadata(Request::class);
$this->em->getUnitOfWork()->computeChangeSet($md, $message->getRequest());
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof Message) {
$this->setLatestMessage($entity);
if (!$entity->shouldNotify()) {
return;
}
// Send a notification email
if ($entity->getAuthor()->isStaff()) {
$user = $entity->getRequest()->getAuthor() === $entity->getAuthor()
? $entity->getRequest()->getRecipient()
: $entity->getRequest()->getAuthor();
if (!$user->getSettings()->isMessengerNotificationSent()) {
$user->getSettings()->setMessengerNotificationSent(true);
$email = $this->mailer->template($user, 'messenger-notification');
$this->mailer->send($email);
}
}
}
}
public function onKernelController(ControllerEvent $event)
{
$controller = $event->getController();
if (!is_array($controller)) {
return;
}
if (!$controller[0] instanceof MessengerController) {
return;
}
// Reset notification lock
$user = $this->storage->getToken()->getUser();
if (!$user instanceof User) {
return;
}
if (!$user->getSettings()->isMessengerNotificationSent()) {
return;
}
$user->getSettings()->setMessengerNotificationSent(false);
$this->em->flush();
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
// Reset notification lock
/** @var User $user */
$user = $event->getAuthenticationToken()->getUser();
if (!$user->getSettings()->isMessengerNotificationSent()) {
return;
}
$user->getSettings()->setMessengerNotificationSent(false);
$this->em->flush();
}
}