<?php
namespace App\EventSubscriber;
use App\Module\Attribute\RequiresModule;
use App\Module\ModuleAccessService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Enforces #[RequiresModule] on controllers. Symfony 6.1 offers no attribute helper on ControllerEvent,
* so the attribute is read by reflection (method-level overrides class-level).
*/
class ModuleAccessSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly ModuleAccessService $moduleAccess,
private readonly UrlGeneratorInterface $urlGenerator,
private readonly TranslatorInterface $translator,
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
public function onKernelController(ControllerEvent $event): void
{
$requirement = $this->getRequirement($event->getController());
if ($requirement === null || $this->moduleAccess->isAccessible($requirement->module)) {
return;
}
$response = $this->buildDeniedResponse($event->getRequest());
$event->setController(static fn (): Response => $response);
}
private function getRequirement(mixed $controller): ?RequiresModule
{
if (is_array($controller) && isset($controller[0], $controller[1])) {
[$object, $method] = $controller;
} elseif (is_object($controller) && !$controller instanceof \Closure) {
$object = $controller;
$method = '__invoke';
} else {
return null;
}
try {
$class = new \ReflectionClass($object);
$reflectionMethod = $class->getMethod($method);
} catch (\ReflectionException) {
return null;
}
$attributes = $reflectionMethod->getAttributes(RequiresModule::class);
if (empty($attributes)) {
$attributes = $class->getAttributes(RequiresModule::class);
}
return empty($attributes) ? null : $attributes[0]->newInstance();
}
private function buildDeniedResponse(Request $request): Response
{
if ($this->wantsJson($request)) {
return new JsonResponse(['error' => true, 'status' => 403, 'message' => 'Module not available'], 403);
}
if ($request->hasSession() && ($session = $request->getSession()) instanceof Session) {
$session->getFlashBag()->add(
'error',
$this->translator->trans('Pages.Common.Alerts.ModuleNotAvailable', [], 'messages_front')
);
}
return new RedirectResponse($this->urlGenerator->generate('app_main'));
}
/**
* XHR, JSON clients (Accept or Content-Type), /api paths and the *_json / *_stream routes called by the React front.
*/
private function wantsJson(Request $request): bool
{
$route = (string) $request->attributes->get('_route');
return $request->isXmlHttpRequest()
|| str_starts_with($request->getPathInfo(), '/api')
|| str_contains($request->getAcceptableContentTypes()[0] ?? '', 'json')
|| str_contains((string) $request->headers->get('Content-Type'), 'json')
|| str_ends_with($route, '_json')
|| str_ends_with($route, '_stream');
}
}