<?php
/*
* This file is part of the nellapp-core package.
*
* (c) Benjamin Georgeault
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nellapp\Bundle\SDKBundle\EventSubscriber;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\Mapping\MappingException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class ControllerEntityResolverSubscriber
*
* @author Benjamin Georgeault
*/
class ControllerEntityResolverSubscriber implements EventSubscriberInterface
{
const REQUEST_KEY = '_entity_resolver';
public function __construct(
private EntityManagerInterface $em,
) {}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER_ARGUMENTS => ['__invoke', 31],
];
}
public function __invoke(ControllerArgumentsEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
if (null === $array = $request->attributes->get(self::REQUEST_KEY)) {
return;
}
if (!is_array($array)) {
throw new \LogicException(sprintf(
'Attribut "_entity_resolver" in route "%s" must be an array.',
$request->attributes->get('_route'),
));
}
foreach ($array as $varName => $class) {
if (!$request->attributes->has($varName)) {
throw new \LogicException(sprintf(
'Missing route variable "%s" in route "%s" for attribut "%s".',
$varName,
$request->attributes->get('_route'),
self::REQUEST_KEY,
));
}
try {
$repo = $this->em->getRepository($class);
} catch (\ReflectionException $e) {
throw new \LogicException(sprintf(
'Class "%s" not found for route variable "%s" in route "%s" for attribut "%s".',
$class,
$varName,
$request->attributes->get('_route'),
self::REQUEST_KEY,
), previous: $e);
} catch (MappingException $e) {
throw new \LogicException(sprintf(
'Class "%s" have no doctrine mapping for route variable "%s" in route "%s" for attribut "%s".',
$class,
$varName,
$request->attributes->get('_route'),
self::REQUEST_KEY,
), previous: $e);
}
if (null === $entity = $repo->find($request->attributes->get($varName))) {
throw new NotFoundHttpException(sprintf(
'Cannot found entity "%s" for id "%s".',
$class,
$request->attributes->get($varName),
));
}
$request->attributes->set($varName, $entity);
}
}
}