<?php
/**
* Created by PhpStorm.
* User: sebastiantovar
* Date: 2019-04-08
* Time: 14:40
*/
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\App\AppParams;
use App\Entity\App\User;
use App\Services\UtilsService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class AppParamsPostValidateSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $utilsService;
public function __construct(
TokenStorageInterface $tokenStorage,
UtilsService $utilsService
) {
$this->tokenStorage = $tokenStorage;
$this->utilsService = $utilsService;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['completeData', EventPriorities::POST_VALIDATE]
];
}
public function completeData(ViewEvent $event)
{
if ($this->utilsService->isAPublicRequest($event)) {
return;
}
$appParams = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$appParams instanceof AppParams || (Request::METHOD_POST !== $method)) {
return;
}
$currentUser = $this->tokenStorage->getToken()->getUser();
if (!$currentUser instanceof User) {
throw new UnauthorizedHttpException('User not found');
}
$appParams->setUser($currentUser);
}
}