<?php
namespace App\EventSubscriber;
use App\Controller\V1\Prospect\AnonymousController;
use App\Controller\V1\Prospect\ProspectAuthenticatedControllerInterface;
use App\Controller\V1\Prospect\RegistrationController;
use App\Repository\Account\TenantPersonRepository;
use App\Service\TenantPerson\TenantPersonService;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class ProspectControllerSubscriber implements EventSubscriberInterface
{
private $tenantPersonRepository;
private $tenantPersonService;
public function __construct(
TenantPersonRepository $tenantPersonRepository,
TenantPersonService $tenantPersonService
) {
$this->tenantPersonRepository = $tenantPersonRepository;
$this->tenantPersonService = $tenantPersonService;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
/**
* @throws NonUniqueResultException
* @throws \Exception
*/
public function onKernelController(ControllerEvent $event)
{
$controller = $event->getController();
$request = $event->getRequest();
// when a controller class defines multiple action methods, the controller
// is returned as [$controllerInstance, 'methodName']
if (is_array($controller)) {
$controller = $controller[0];
}
if ($controller instanceof RegistrationController || $controller instanceof AnonymousController) {
return;
}
if ($controller instanceof ProspectAuthenticatedControllerInterface) {
$forbidden = new AccessDeniedHttpException("You don't have permission to access the server.");
if (!$request->headers->has('X-TP-ID')) {
throw $forbidden;
}
$prospectTenantPersonId = $request->headers->get('X-TP-ID');
if (!is_numeric($prospectTenantPersonId)) {
throw $forbidden;
}
$tenantPerson = $this->tenantPersonRepository->findOneByProspectTenantPersonId($prospectTenantPersonId);
if (!$tenantPerson) {
throw $forbidden;
}
if ($this->tenantPersonService->isInitialized()) {
return;
}
$this->tenantPersonService->init($tenantPerson);
}
}
}