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

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