<?php
namespace App\EventSubscriber\Ticket;
use App\Services\UtilsService;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\KernelEvents;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Exception\AccessDeniedException;
use App\Exception\NotFoundException;
use App\Services\VendorService;
use App\Entity\App\Ticket\IncidenceType;
use App\Entity\App\User;
use App\Entity\App\Role;
use Symfony\Contracts\Translation\TranslatorInterface;
class IncidenceTypePreWriteSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $authorizationChecker;
private $vendorService;
private $utilsService;
private $translator;
public function __construct(
TokenStorageInterface $tokenStorage,
AuthorizationCheckerInterface $checker,
VendorService $vendorService,
UtilsService $utilsService,
TranslatorInterface $translator
)
{
$this->tokenStorage = $tokenStorage;
$this->authorizationChecker = $checker;
$this->vendorService = $vendorService;
$this->utilsService = $utilsService;
$this->translator = $translator;
}
/**
* @param ViewEvent $event
* @throws AccessDeniedException
* @throws NotFoundException
*/
public function onKernelView(ViewEvent $event)
{
//Don't change the place of this if
if ($this->utilsService->isAPublicRequest($event)) {
return;
}
$incidenceType = $event->getControllerResult();
$request = $event->getRequest();
$method = $request->getMethod();
$userCurrent = $this->tokenStorage->getToken()->getUser();
if (!($incidenceType instanceof IncidenceType) ||
(Request::METHOD_POST !== $method && Request::METHOD_PUT !== $method && Request::METHOD_DELETE !== $method))
return;
if ($this->authorizationChecker->isGranted('ROLE_SUPERADMIN'))
return;
if (!$userCurrent instanceof User)
throw new NotFoundException($this->translator->trans('User not found'));
if (!$this->vendorService->isUserRoleInToVendor($incidenceType->getVendor(), $userCurrent, [Role::ROLE_ADMIN]))
throw new AccessDeniedException($this->translator->trans('Access denied'));
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::PRE_WRITE]
];
}
}