vendor/easycorp/easyadmin-bundle/src/EventListener/ControllerListener.php line 34

Open in your IDE?
  1. <?php
  2. namespace EasyCorp\Bundle\EasyAdminBundle\EventListener;
  3. use EasyCorp\Bundle\EasyAdminBundle\Configuration\ConfigManager;
  4. use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
  5. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  6. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  7. /**
  8.  * Sets the right controller to be executed when entities define custom
  9.  * controllers.
  10.  *
  11.  * @author Yonel Ceruto <yonelceruto@gmail.com>
  12.  */
  13. class ControllerListener
  14. {
  15.     private $configManager;
  16.     private $resolver;
  17.     public function __construct(ConfigManager $configManagerControllerResolverInterface $resolver)
  18.     {
  19.         $this->configManager $configManager;
  20.         $this->resolver $resolver;
  21.     }
  22.     /**
  23.      * Exchange default admin controller by custom entity admin controller.
  24.      *
  25.      * @param ControllerEvent $event
  26.      *
  27.      * @throws NotFoundHttpException
  28.      */
  29.     public function onKernelController($event)
  30.     {
  31.         $request $event->getRequest();
  32.         if ('easyadmin' !== $request->attributes->get('_route')) {
  33.             return;
  34.         }
  35.         $currentController $event->getController();
  36.         // if the controller is defined in a class, $currentController is an array
  37.         // otherwise do nothing because it's a Closure (rare but possible in Symfony)
  38.         if (!\is_array($currentController)) {
  39.             return;
  40.         }
  41.         // this condition happens when accessing the backend homepage, which
  42.         // then redirects to the 'list' action of the first configured entity.
  43.         if (null === $entityName $request->query->get('entity')) {
  44.             return;
  45.         }
  46.         $entity $this->configManager->getEntityConfig($entityName);
  47.         // if the entity doesn't define a custom controller, do nothing
  48.         if (!isset($entity['controller'])) {
  49.             return;
  50.         }
  51.         // build the full controller name using the 'class::method' syntax
  52.         $controllerMethod $currentController[1];
  53.         $customController $entity['controller'].'::'.$controllerMethod;
  54.         $request->attributes->set('_controller'$customController);
  55.         $newController $this->resolver->getController($request);
  56.         if (false === $newController) {
  57.             throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". Check the "controller" configuration of the "%s" entity in your EasyAdmin backend.'$request->getPathInfo(), $entityName));
  58.         }
  59.         $event->setController($newController);
  60.     }
  61. }