ecommerce121/util-bundle/Model/Form/EntityBuilderValidationListener.php line 43

  1. <?php
  2. namespace Ecommerce121\UtilBundle\Model\Form;
  3. use Ecommerce121\UtilBundle\Model\Builder\EntityBuilder;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\Form\FormError;
  6. use Symfony\Component\Form\FormEvent;
  7. use Symfony\Component\Form\FormEvents;
  8. use Symfony\Component\Validator\Validator\ValidatorInterface;
  9. use Symfony\Component\Validator\ValidatorInterface as LegacyValidatorInterface;
  10. /**
  11. * Listener that validates the associated entity after the form is validated.
  12. */
  13. class EntityBuilderValidationListener implements EventSubscriberInterface
  14. {
  15. private $validator;
  16. /**
  17. * {@inheritdoc}
  18. */
  19. public static function getSubscribedEvents(): array
  20. {
  21. return array(FormEvents::POST_SUBMIT => 'validateForm');
  22. }
  23. /**
  24. * Constructor.
  25. *
  26. * @param ValidatorInterface|LegacyValidatorInterface $validator
  27. */
  28. public function __construct(ValidatorInterface $validator)
  29. {
  30. $this->validator = $validator;
  31. }
  32. /**
  33. * Validates the form and its domain object.
  34. *
  35. * @param FormEvent $event The event object
  36. */
  37. public function validateForm(FormEvent $event): void
  38. {
  39. $form = $event->getForm();
  40. $builder = $form->getData();
  41. if ($form->isRoot() && $form->isValid() && $builder instanceof EntityBuilder) {
  42. $builder->build();
  43. $violations = $this->validator->validate($builder->getEntity());
  44. foreach ($violations as $violation) {
  45. $form->addError(new FormError(
  46. $violation->getMessage(),
  47. $violation->getMessageTemplate(),
  48. $violation->getParameters(),
  49. $violation->getPlural(),
  50. $violation
  51. ));
  52. }
  53. }
  54. }
  55. }