<?php
/*
* This file is part of the drosalys/api-bundle package.
*
* (c) Benjamin Georgeault
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Drosalys\Bundle\ApiBundle\EventSubscriber;
use Drosalys\Bundle\ApiBundle\Action\ActionRetriever;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
/**
* Class ActionControllerSubscriber
*
* @author Benjamin Georgeault
*/
class ActionControllerSubscriber implements EventSubscriberInterface
{
const REQUEST_KEY = '_drosalys_api_action';
public function __construct(
private ActionRetriever $actionRetriever,
private RouterInterface $router,
) {}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => ['__invoke', 15],
];
}
public function __invoke(ControllerEvent $event): void
{
if ($this->actionRetriever->hasActionController($controller = $event->getController())) {
$request = $event->getRequest();
$routeName = $request->attributes->get('_route');
if (null === $route = $this->router->getRouteCollection()->get($routeName)) {
return;
}
if (null === $action = $this->actionRetriever->retrieveFromController($controller, $route)) {
return;
}
if ($action->needController()) {
$action->setController($this->extractObject($controller));
}
$request->attributes->set(self::REQUEST_KEY, $action);
}
}
private function extractObject(callable $controller): object
{
if (is_object($controller)) {
return $controller;
}
if (is_array($controller)) {
return $controller[0];
}
throw new \RuntimeException('Cannot convert callable to object.');
}
}