<?php
namespace Cms\ModuleBundle\Request\ParamConverter;
use Cms\ContainerBundle\Entity\Container;
use Cms\CoreBundle\Util\Doctrine\EntityManager;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Class ContainerConverter
* @package Cms\ModuleBundle\Request\ParamConverter
*/
final class ContainerConverter implements ParamConverterInterface
{
/**
* @var EntityManager
*/
private EntityManager $em;
/**
* @param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* {@inheritdoc}
*/
public function apply(Request $request, ParamConverter $configuration): bool
{
$name = $configuration->getName();
$class = $configuration->getClass();
if ( ! $request->attributes->has($name)) {
throw new \LogicException();
}
$value = $request->attributes->get($name);
$entity = $value ? $this->em->getRepository($class)->find($value) : null;
if ($entity && ! $entity instanceof Container) {
throw new \LogicException();
}
if ($entity && ! $entity instanceof $class) {
throw new \LogicException();
}
if ($entity) {
$request->attributes->set($name, $entity);
}
return (bool) $entity;
}
/**
* {@inheritdoc}
*/
public function supports(ParamConverter $configuration): bool
{
if (empty($configuration->getClass())) {
return false;
}
return $configuration->getClass() === Container::class || is_subclass_of($configuration->getClass(), Container::class);
}
}