src/Hitso/Bundle/FormBundle/Form/Handler/FormHandler.php line 43

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Hitso\Bundle\FormBundle\Form\Handler;
  4. use Doctrine\Common\Inflector\Inflector;
  5. use Hitso\Bundle\CommonBundle\Entity\EntityInterface;
  6. use Hitso\Bundle\FormBundle\Event\FormEvent;
  7. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  8. use Symfony\Component\Form\FormFactoryInterface;
  9. use Symfony\Component\Form\FormInterface;
  10. final class FormHandler implements FormHandlerInterface
  11. {
  12.     /**
  13.      * @var EventDispatcherInterface
  14.      */
  15.     private $eventDispatcher;
  16.     /**
  17.      * @var FormFactoryInterface
  18.      */
  19.     private $formFactory;
  20.     /**
  21.      * FormHandler constructor.
  22.      *
  23.      * @param EventDispatcherInterface $eventDispatcher
  24.      * @param FormFactoryInterface     $formFactory
  25.      */
  26.     public function __construct(EventDispatcherInterface $eventDispatcherFormFactoryInterface $formFactory)
  27.     {
  28.         $this->eventDispatcher $eventDispatcher;
  29.         $this->formFactory     $formFactory;
  30.     }
  31.     public function createForm(EntityInterface $data, array $options = [], string $formTypestring $eventName null): FormInterface
  32.     {
  33.         if (null === $eventName) {
  34.             $eventName $this->getEventName($formTypeself::FORM_INIT_EVENT);
  35.         }
  36.         $builder $this->formFactory->createBuilder($formType$data$options);
  37.         $this->eventDispatcher->dispatch($eventName, new FormEvent($builder));
  38.         return $builder->getForm();
  39.     }
  40.     private function getEventName(string $type$name): string
  41.     {
  42.         $eventName = (new \ReflectionClass($type))->getShortName();
  43.         return sprintf('%s.%s'Inflector::tableize($eventName), $name);
  44.     }
  45. }