<?php
namespace App\EventSubscriber;
use App\Entity\PredefinedColor;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RichFieldSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
protected $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* @param RequestEvent $event
*
* @throws Exception
*/
public function onKernelRequest(RequestEvent $event)
{
$richType = $event->getRequest()->get('richType');
if ($richType) {
$value = $event->getRequest()->request->get('value');
if (!$value instanceof $richType) {
$colorId = (int)$value['color'];
$color = $this->entityManager->getRepository(PredefinedColor::class)->find(
($colorId > 0 ? $colorId : 1)
);
$value = new $richType(new DateTime($value['value']), $color);
}
$event->getRequest()->request->set('value', $value);
}
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
}