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

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