vendor/drosalys/api-bundle/src/EventSubscriber/ActionControllerSubscriber.php line 41

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the drosalys/api-bundle package.
  4.  *
  5.  * (c) Benjamin Georgeault
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Drosalys\Bundle\ApiBundle\EventSubscriber;
  11. use Drosalys\Bundle\ApiBundle\Action\ActionRetriever;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. use Symfony\Component\Routing\RouterInterface;
  16. /**
  17.  * Class ActionControllerSubscriber
  18.  *
  19.  * @author Benjamin Georgeault
  20.  */
  21. class ActionControllerSubscriber implements EventSubscriberInterface
  22. {
  23.     const REQUEST_KEY '_drosalys_api_action';
  24.     public function __construct(
  25.         private ActionRetriever $actionRetriever,
  26.         private RouterInterface $router,
  27.     ) {}
  28.     public static function getSubscribedEvents(): array
  29.     {
  30.         return [
  31.             KernelEvents::CONTROLLER => ['__invoke'15],
  32.         ];
  33.     }
  34.     public function __invoke(ControllerEvent $event): void
  35.     {
  36.         if ($this->actionRetriever->hasActionController($controller $event->getController())) {
  37.             $request $event->getRequest();
  38.             $routeName $request->attributes->get('_route');
  39.             if (null === $route $this->router->getRouteCollection()->get($routeName)) {
  40.                 return;
  41.             }
  42.             if (null === $action $this->actionRetriever->retrieveFromController($controller$route)) {
  43.                 return;
  44.             }
  45.             if ($action->needController()) {
  46.                 $action->setController($this->extractObject($controller));
  47.             }
  48.             $request->attributes->set(self::REQUEST_KEY$action);
  49.         }
  50.     }
  51.     private function extractObject(callable $controller): object
  52.     {
  53.         if (is_object($controller)) {
  54.             return $controller;
  55.         }
  56.         if (is_array($controller)) {
  57.             return $controller[0];
  58.         }
  59.         throw new \RuntimeException('Cannot convert callable to object.');
  60.     }
  61. }