<?php
namespace App\EventSubscriber;
use App\Utils\RequestHelper;
use App\Domain\Payload\Error;
use App\Exception\ApiException;
use App\Domain\Payload\Payload;
use App\Exception\ApiExceptionInterface;
use App\Domain\Exception\Restrict\RestrictException;
use App\Services\RoutePermissions\RoutePermissionValidator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
class AccessCheckSubscriber implements EventSubscriberInterface
{
/**
* @var RoutePermissionValidator
*/
private $permissionValidator;
/**
* @var RequestHelper
*/
private $requestHelper;
public function __construct(RoutePermissionValidator $permissionValidator, RequestHelper $requestHelper)
{
$this->permissionValidator = $permissionValidator;
$this->requestHelper = $requestHelper;
}
/**
* @throws RestrictException|ApiExceptionInterface
*/
public function onController(ControllerEvent $event): void
{
$givenRoute = $event->getRequest()->getPathInfo();
if (!$this->permissionValidator->validate($givenRoute)) {
if ($this->requestHelper->isV1Route()) {
throw new RestrictException('No permissions to access this endpoint');
}
$payload = new Payload();
$payload->setError(new Error(0, 'No permissions to access this endpoint'));
throw ApiException::createForbiddenException($payload);
}
}
public static function getSubscribedEvents(): array
{
return [
'kernel.controller' => ['onController', 1],
];
}
}