<?php
namespace App\EventSubscriber;
use App\Enum\UserRole;
use App\Enum\ErrorResponseMessageEnum;
use App\Service\UserInterface;
use App\Service\FrontendService;
use App\Controller\RepresentativeAuthenticatedController;
use App\Exception\RoleRepresentativeRequiredException;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
class RepresentativeAuthenticatedSubscriber implements EventSubscriberInterface
{
private $userService;
private $frontendService;
public function __construct(UserInterface $userService, FrontendService $frontendService){
$this->userService = $userService;
$this->frontendService = $frontendService;
}
public function onKernelController(ControllerEvent $event)
{
$controller = $event->getController();
/*
* $controller passed can be either a class or a Closure.
* This is not usual in Symfony but it may happen.
* If it is a class, it comes in array format
*/
if (!is_array($controller)) {
return;
}
if ($controller[0] instanceof RepresentativeAuthenticatedController) {
if (!$this->userService->isAccessGranted(UserRole::ROLE_REPRESENTATIVE)){
throw new RoleRepresentativeRequiredException();
}
}
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::CONTROLLER => 'onKernelController',
KernelEvents::EXCEPTION => array(
array('roleRepresentativeRequiredException', 0),
)
);
}
public function roleRepresentativeRequiredException(ExceptionEvent $event)
{
if ($event->getThrowable() instanceof RoleRepresentativeRequiredException){
$event->setResponse($this->frontendService->forbidden(ErrorResponseMessageEnum::ROLE_REPRESENTATIVE_REQUIRED));
}
}
}