src/EventSubscriber/AppParamsPostValidateSubscriber.php line 45

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: sebastiantovar
  5.  * Date: 2019-04-08
  6.  * Time: 14:40
  7.  */
  8. namespace App\EventSubscriber;
  9. use ApiPlatform\Core\EventListener\EventPriorities;
  10. use App\Entity\App\AppParams;
  11. use App\Entity\App\User;
  12. use App\Services\UtilsService;
  13. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpKernel\Event\ViewEvent;
  16. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  17. use Symfony\Component\HttpKernel\KernelEvents;
  18. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  19. class AppParamsPostValidateSubscriber implements EventSubscriberInterface
  20. {
  21.     private $tokenStorage;
  22.     private $utilsService;
  23.     public function __construct(
  24.         TokenStorageInterface $tokenStorage,
  25.         UtilsService $utilsService
  26.     ) {
  27.         $this->tokenStorage $tokenStorage;
  28.         $this->utilsService $utilsService;
  29.     }
  30.     /**
  31.      * {@inheritdoc}
  32.      */
  33.     public static function getSubscribedEvents()
  34.     {
  35.         return [
  36.             KernelEvents::VIEW => ['completeData'EventPriorities::POST_VALIDATE]
  37.         ];
  38.     }
  39.     public function completeData(ViewEvent $event)
  40.     {
  41.         if ($this->utilsService->isAPublicRequest($event)) {
  42.             return;
  43.         }
  44.         $appParams $event->getControllerResult();
  45.         $method $event->getRequest()->getMethod();
  46.         if (!$appParams instanceof AppParams || (Request::METHOD_POST !== $method)) {
  47.             return;
  48.         }
  49.         $currentUser $this->tokenStorage->getToken()->getUser();
  50.         if (!$currentUser instanceof User) {
  51.             throw new UnauthorizedHttpException('User not found');
  52.         }
  53.         $appParams->setUser($currentUser);
  54.     }
  55. }