<?php
/**
* Created by PhpStorm.
* User: SUSAN MEDINA
* Date: 21/05/2019
* Time: 02:15 PM
*/
namespace App\EventSubscriber\ChatMessage;
use App\Entity\App\User;
use App\Entity\Chat\Chat;
use App\Exception\NotFoundException;
use App\Repository\Chat\ChatRepository;
use App\Services\UtilsService;
use App\Services\ChatService;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\KernelEvents;
class ChatMessagePreSerializeSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $authorizationChecker;
private $chatService;
private $utilsService;
private $translator;
private $chatRepository;
public function __construct(
TokenStorageInterface $tokenStorage,
AuthorizationCheckerInterface $checker,
ChatService $chatService,
UtilsService $utilsService,
TranslatorInterface $translator,
ChatRepository $chatRepository)
{
$this->tokenStorage = $tokenStorage;
$this->authorizationChecker = $checker;
$this->chatService = $chatService;
$this->utilsService = $utilsService;
$this->translator = $translator;
$this->chatRepository = $chatRepository;
}
/**
* @param ViewEvent $event
* @throws NotFoundException
*/
public function onKernelView(ViewEvent $event)
{
if ($this->utilsService->isAPublicRequest($event)) {
return;
}
$request = $event->getRequest();
$method = $request->getMethod();
$userCurrent = $this->tokenStorage->getToken()->getUser();
if (Request::METHOD_GET !== $method)
return;
$routes = array('api_chats_messages_get_subresource');
$route = $request->attributes->get('_route');
if (!in_array($route, $routes))
return;
$chatId = $route = $request->attributes->get('id');
$chat = $this->chatRepository->findOneBy(['id' => $chatId]);
if (!$chat instanceof Chat) {
throw new NotFoundException($this->translator->trans('entity_not_found', ['%entity%' => 'chat']));
}
if (!$userCurrent instanceof User) {
throw new NotFoundException($this->translator->trans('User current not found'));
}
$this->chatService->markMessagesAsReadByChatAndUser($chat, $userCurrent);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::PRE_SERIALIZE]
];
}
}