<?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 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;
use App\Services\ChatService;
class ChatMessagePostSerializeSubscriber 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
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function onKernelView(ViewEvent $event)
{
if ($this->utilsService->isAPublicRequest($event)) {
return;
}
$chatMessage = $event->getControllerResult();
$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;
}
if (!$userCurrent instanceof User) {
throw new NotFoundException($this->translator->trans('User not found'));
}
$chatId = $route = $request->attributes->get('id');
$chat = $this->chatRepository->findOneBy(['id' => $chatId]);
if (!$chat instanceof Chat) {
return;
}
$locale = $userCurrent->getLocale();
if ($request->query->has('locale') &&
in_array(strtolower($request->query->get('locale')), [User::LOCALE_EN, User::LOCALE_ES])
) {
$locale = strtolower($request->query->get('locale'));
}
$chatMessageResult = json_decode($chatMessage, true);
$order = $request->query->get('order') ?? [];
if (isset($order['createdAt']) && isset($order['id'])) {
if ($order['id'] === 'asc') {
$chatMessageResult = $this->sorting($chatMessageResult, true);
}
if ($order['id'] === 'desc') {
$chatMessageResult = $this->sorting($chatMessageResult, false);
}
}
foreach ($chatMessageResult as &$message) {
if ($message['type'] === 'log') {
$body = $message['body'];
if (is_string($body)) {
$body = json_decode($message['body'], true);
}
$parameters = [];
if (isset($body['parameters'])) {
$parameters = $body['parameters'];
}
if (isset($body['parametersTrans'])) {
foreach ($body['parametersTrans'] as $key => $value) {
$parameters[$key] = $this->translator->trans($value, [], null, $userCurrent->getLocale());
}
}
if (isset($body['message'])) {
$message['body'] = $this->translator->trans(
$body['message'],
$parameters,
null,
$locale
);
}
}
}
$chatMessageResultMain['messages'] = $chatMessageResult;
$chatMessageResultMain['messagesPendingToReadGlobalCounter'] = $this->chatService->calculateMessagesPendingToReadForAllChats(
$userCurrent
);
$chatMessageResultMain['messagesPendingToReadCounter'] = $this->chatService->calculateMessagesPendingToReadForChat(
$chat,
$userCurrent
);
$chatMessageResultMain = json_encode($chatMessageResultMain);
$event->setControllerResult($chatMessageResultMain);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::POST_SERIALIZE]
];
}
protected function sorting($array, $ascending = true)
{
$ids = [];
foreach ($array as $key => $value) {
$ids[$key] = $value['id'];
}
if ($ascending) {
asort($ids);
} else {
arsort($ids);
}
$result = [];
foreach ($ids as $index => $values) {
$result[] = $array[$index];
}
if (count($result) === 0) {
$result = $array;
}
return $result;
}
}