<?php
namespace App\EventSubscriber;
use App\Entity\Company;
use App\Security\UserSecurityHelper;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
class AdminCompanyImpersonationSubscriber implements EventSubscriberInterface
{
private const string HEADER_NAME = 'X-Company-Id';
public function __construct(
private readonly UserSecurityHelper $securityHelper,
private readonly EntityManagerInterface $entityManager
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 7], // Execute before security checks
];
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
try {
if (!$this->securityHelper->isGranted('ROLE_ADMIN')) {
return;
}
$request = $event->getRequest();
$galabCustomerId = $request->headers->get(self::HEADER_NAME);
if (!$galabCustomerId) {
return;
}
$company = $this->entityManager->getRepository(Company::class)
->findOneBy(['galabCustomerId' => $galabCustomerId]);
if (!$company) {
return;
}
// Store the impersonated company in the request attributes
$request->attributes->set('impersonated_company', $company);
} catch (AuthenticationCredentialsNotFoundException) {
}
}
}