<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\Response;
use App\Entity\Customer;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class AcceptedTermListener implements EventSubscriberInterface
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
if (preg_match('/^\/api/', $request->getPathInfo()) && $token = $this->tokenStorage->getToken()) {
/** @var Customer $customer */
$customer = $token->getUser();
if (!$customer->getAcceptedTerm() && !in_array('ROLE_ADMIN', $customer->getRoles())) {
throw new \Exception('User term not accepted', Response::HTTP_FORBIDDEN);
}
}
}
/**
* @return mixed[]
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
}