<?php
declare(strict_types=1);
namespace Hitso\Bundle\FormBundle\Form\Handler;
use Doctrine\Common\Inflector\Inflector;
use Hitso\Bundle\CommonBundle\Entity\EntityInterface;
use Hitso\Bundle\FormBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
final class FormHandler implements FormHandlerInterface
{
/**
* @var EventDispatcherInterface
*/
private $eventDispatcher;
/**
* @var FormFactoryInterface
*/
private $formFactory;
/**
* FormHandler constructor.
*
* @param EventDispatcherInterface $eventDispatcher
* @param FormFactoryInterface $formFactory
*/
public function __construct(EventDispatcherInterface $eventDispatcher, FormFactoryInterface $formFactory)
{
$this->eventDispatcher = $eventDispatcher;
$this->formFactory = $formFactory;
}
public function createForm(EntityInterface $data, array $options = [], string $formType, string $eventName = null): FormInterface
{
if (null === $eventName) {
$eventName = $this->getEventName($formType, self::FORM_INIT_EVENT);
}
$builder = $this->formFactory->createBuilder($formType, $data, $options);
$this->eventDispatcher->dispatch($eventName, new FormEvent($builder));
return $builder->getForm();
}
private function getEventName(string $type, $name): string
{
$eventName = (new \ReflectionClass($type))->getShortName();
return sprintf('%s.%s', Inflector::tableize($eventName), $name);
}
}