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

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