vendor/easycorp/easyadmin-bundle/src/EventListener/AdminRouterSubscriber.php line 76

Open in your IDE?
  1. <?php
  2. namespace EasyCorp\Bundle\EasyAdminBundle\EventListener;
  3. use EasyCorp\Bundle\EasyAdminBundle\Config\Option\EA;
  4. use EasyCorp\Bundle\EasyAdminBundle\Contracts\Controller\CrudControllerInterface;
  5. use EasyCorp\Bundle\EasyAdminBundle\Contracts\Controller\DashboardControllerInterface;
  6. use EasyCorp\Bundle\EasyAdminBundle\Factory\AdminContextFactory;
  7. use EasyCorp\Bundle\EasyAdminBundle\Factory\ControllerFactory;
  8. use EasyCorp\Bundle\EasyAdminBundle\Registry\CrudControllerRegistry;
  9. use EasyCorp\Bundle\EasyAdminBundle\Registry\DashboardControllerRegistry;
  10. use EasyCorp\Bundle\EasyAdminBundle\Router\UrlSigner;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
  14. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  15. use Symfony\Component\HttpKernel\Event\RequestEvent;
  16. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  17. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  18. use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
  19. use Twig\Environment;
  20. /**
  21.  * This subscriber acts as a "proxy" of all backend requests. First, if the
  22.  * request is related to EasyAdmin, it creates the AdminContext variable and
  23.  * stores it in the Request as an attribute.
  24.  *
  25.  * Second, it uses Symfony events to serve all backend requests using a single
  26.  * route. The trick is to change dynamically the controller to execute when
  27.  * the request is related to a CRUD action or a normal Symfony route/action.
  28.  *
  29.  * @author Javier Eguiluz <javier.eguiluz@gmail.com>
  30.  * @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
  31.  * @author Yonel Ceruto <yonelceruto@gmail.com>
  32.  */
  33. class AdminRouterSubscriber implements EventSubscriberInterface
  34. {
  35.     private AdminContextFactory $adminContextFactory;
  36.     private DashboardControllerRegistry $dashboardControllerRegistry;
  37.     private CrudControllerRegistry $crudControllerRegistry;
  38.     private ControllerFactory $controllerFactory;
  39.     private ControllerResolverInterface $controllerResolver;
  40.     private UrlGeneratorInterface $urlGenerator;
  41.     private RequestMatcherInterface $requestMatcher;
  42.     private Environment $twig;
  43.     private UrlSigner $urlSigner;
  44.     public function __construct(AdminContextFactory $adminContextFactoryDashboardControllerRegistry $dashboardControllerRegistryCrudControllerRegistry $crudControllerRegistryControllerFactory $controllerFactoryControllerResolverInterface $controllerResolverUrlGeneratorInterface $urlGeneratorRequestMatcherInterface $requestMatcherEnvironment $twigUrlSigner $urlSigner)
  45.     {
  46.         $this->adminContextFactory $adminContextFactory;
  47.         $this->dashboardControllerRegistry $dashboardControllerRegistry;
  48.         $this->crudControllerRegistry $crudControllerRegistry;
  49.         $this->controllerFactory $controllerFactory;
  50.         $this->controllerResolver $controllerResolver;
  51.         $this->urlGenerator $urlGenerator;
  52.         $this->requestMatcher $requestMatcher;
  53.         $this->twig $twig;
  54.         $this->urlSigner $urlSigner;
  55.     }
  56.     public static function getSubscribedEvents(): array
  57.     {
  58.         return [
  59.             RequestEvent::class => [
  60.                 ['onKernelRequest'0],
  61.             ],
  62.             // the priority must be higher than 0 to run it before ParamConverterListener
  63.             ControllerEvent::class => ['onKernelController'128],
  64.         ];
  65.     }
  66.     /**
  67.      * If this is an EasyAdmin request, it creates the AdminContext variable, stores it
  68.      * in the Request as an attribute and injects it as a global Twig variable.
  69.      */
  70.     public function onKernelRequest(RequestEvent $event): void
  71.     {
  72.         $request $event->getRequest();
  73.         if (null === $dashboardControllerFqcn $this->getDashboardControllerFqcn($request)) {
  74.             return;
  75.         }
  76.         if (null === $dashboardControllerInstance $this->getDashboardControllerInstance($dashboardControllerFqcn$request)) {
  77.             return;
  78.         }
  79.         // creating the context is expensive, so it's created once and stored in the request
  80.         // if the current request already has an AdminContext object, do nothing
  81.         if (null === $adminContext $request->attributes->get(EA::CONTEXT_REQUEST_ATTRIBUTE)) {
  82.             $crudControllerInstance $this->getCrudControllerInstance($request);
  83.             $adminContext $this->adminContextFactory->create($request$dashboardControllerInstance$crudControllerInstance);
  84.         }
  85.         $request->attributes->set(EA::CONTEXT_REQUEST_ATTRIBUTE$adminContext);
  86.         // this makes the AdminContext available in all templates as a short named variable
  87.         $this->twig->addGlobal('ea'$adminContext);
  88.         if ($adminContext->getSignedUrls() && false === $this->urlSigner->check($request->getUri())) {
  89.             throw new AccessDeniedHttpException('The signature of the URL is not valid.');
  90.         }
  91.     }
  92.     /**
  93.      * In EasyAdmin all backend requests are served via the same route (that allows to
  94.      * detect under which dashboard you want to process the request). This method handles
  95.      * the requests related to "CRUD controller actions" and "custom Symfony actions".
  96.      * The trick used is to change dynamically the controller executed by Symfony.
  97.      */
  98.     public function onKernelController(ControllerEvent $event): void
  99.     {
  100.         $request $event->getRequest();
  101.         if (null === $request->attributes->get(EA::CONTEXT_REQUEST_ATTRIBUTE)) {
  102.             return;
  103.         }
  104.         // if the request is related to a CRUD controller, change the controller to be executed
  105.         if (null !== $crudControllerInstance $this->getCrudControllerInstance($request)) {
  106.             $symfonyControllerFqcnCallable = [$crudControllerInstance$request->query->get(EA::CRUD_ACTION)];
  107.             $symfonyControllerStringCallable = [\get_class($crudControllerInstance), $request->query->get(EA::CRUD_ACTION)];
  108.             // this makes Symfony believe that another controller is being executed
  109.             // (e.g. this is needed for the autowiring of controller action arguments)
  110.             // VERY IMPORTANT: here the Symfony controller must be passed as a string (['App\Controller\Foo', 'index'])
  111.             // Otherwise, the param converter of the controller method doesn't work
  112.             $event->getRequest()->attributes->set('_controller'$symfonyControllerStringCallable);
  113.             // this actually makes Symfony to execute the other controller
  114.             $event->setController($symfonyControllerFqcnCallable);
  115.         }
  116.         // if the request is related to a custom action, change the controller to be executed
  117.         if (null !== $request->query->get(EA::ROUTE_NAME)) {
  118.             $symfonyControllerAsString $this->getSymfonyControllerFqcn($request);
  119.             $symfonyControllerCallable $this->getSymfonyControllerInstance($symfonyControllerAsString$request->query->all()[EA::ROUTE_PARAMS] ?? []);
  120.             if (false !== $symfonyControllerCallable) {
  121.                 // this makes Symfony believe that another controller is being executed
  122.                 // (e.g. this is needed for the autowiring of controller action arguments)
  123.                 // VERY IMPORTANT: here the Symfony controller must be passed as a string ('App\Controller\Foo::index')
  124.                 // Otherwise, the param converter of the controller method doesn't work
  125.                 $event->getRequest()->attributes->set('_controller'$symfonyControllerAsString);
  126.                 // route params must be added as route attribute; otherwise, param converters don't work
  127.                 $event->getRequest()->attributes->replace(array_merge(
  128.                     $request->query->all()[EA::ROUTE_PARAMS] ?? [],
  129.                     $event->getRequest()->attributes->all()
  130.                 ));
  131.                 // this actually makes Symfony to execute the other controller
  132.                 $event->setController($symfonyControllerCallable);
  133.             }
  134.         }
  135.     }
  136.     /**
  137.      * It returns the FQCN of the EasyAdmin Dashboard controller used to serve this
  138.      * request or null if this is not an EasyAdmin request.
  139.      * Because of how EasyAdmin works, all backend requests are handled via the
  140.      * Dashboard controller, so its enough to check if the request controller implements
  141.      * the DashboardControllerInterface.
  142.      */
  143.     private function getDashboardControllerFqcn(Request $request): ?string
  144.     {
  145.         $controller $request->attributes->get('_controller');
  146.         $controllerFqcn null;
  147.         if (\is_string($controller)) {
  148.             [$controllerFqcn, ] = explode('::'$controller);
  149.         }
  150.         if (\is_array($controller)) {
  151.             $controllerFqcn $controller[0];
  152.         }
  153.         if (\is_object($controller)) {
  154.             $controllerFqcn \get_class($controller);
  155.         }
  156.         return is_subclass_of($controllerFqcnDashboardControllerInterface::class) ? $controllerFqcn null;
  157.     }
  158.     private function getDashboardControllerInstance(string $dashboardControllerFqcnRequest $request): ?DashboardControllerInterface
  159.     {
  160.         return $this->controllerFactory->getDashboardControllerInstance($dashboardControllerFqcn$request);
  161.     }
  162.     private function getCrudControllerInstance(Request $request): ?CrudControllerInterface
  163.     {
  164.         if (null !== $crudId $request->query->get(EA::CRUD_ID)) {
  165.             $crudControllerFqcn $this->crudControllerRegistry->findCrudFqcnByCrudId($crudId);
  166.         } else {
  167.             $crudControllerFqcn $request->query->get(EA::CRUD_CONTROLLER_FQCN);
  168.         }
  169.         $crudAction $request->query->get(EA::CRUD_ACTION);
  170.         return $this->controllerFactory->getCrudControllerInstance($crudControllerFqcn$crudAction$request);
  171.     }
  172.     private function getSymfonyControllerFqcn(Request $request): ?string
  173.     {
  174.         $routeName $request->query->get(EA::ROUTE_NAME);
  175.         $routeParams $request->query->all()[EA::ROUTE_PARAMS] ?? [];
  176.         $url $this->urlGenerator->generate($routeName$routeParams);
  177.         $newRequest $request->duplicate();
  178.         $newRequest->attributes->remove('_controller');
  179.         $newRequest->attributes->set('_route'$routeName);
  180.         $newRequest->attributes->add($routeParams);
  181.         $newRequest->server->set('REQUEST_URI'$url);
  182.         $parameters $this->requestMatcher->matchRequest($newRequest);
  183.         return $parameters['_controller'] ?? null;
  184.     }
  185.     private function getSymfonyControllerInstance(string $controllerFqcn, array $routeParams): callable|false
  186.     {
  187.         $newRequest = new Request([], [], ['_controller' => $controllerFqcn'_route_params' => $routeParams], [], [], []);
  188.         return $this->controllerResolver->getController($newRequest);
  189.     }
  190. }