src/EventListener/AcceptedTermListener.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use App\Entity\Customer;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  9. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  10. class AcceptedTermListener implements EventSubscriberInterface
  11. {
  12.     private $tokenStorage;
  13.     public function __construct(TokenStorageInterface $tokenStorage)
  14.     {
  15.         $this->tokenStorage $tokenStorage;
  16.     }
  17.     public function onKernelRequest(RequestEvent $event): void
  18.     {
  19.         $request  $event->getRequest();
  20.         if (preg_match('/^\/api/'$request->getPathInfo()) && $token $this->tokenStorage->getToken()) {
  21.             /** @var Customer $customer */
  22.             $customer $token->getUser();
  23.             if (!$customer->getAcceptedTerm() && !in_array('ROLE_ADMIN'$customer->getRoles())) {
  24.                 throw new \Exception('User term not accepted'Response::HTTP_FORBIDDEN);
  25.             }
  26.         }
  27.     }
  28.     /**
  29.      * @return mixed[]
  30.      */
  31.     public static function getSubscribedEvents()
  32.     {
  33.         return [
  34.             KernelEvents::REQUEST => 'onKernelRequest',
  35.         ];
  36.     }
  37. }