vendor/symfony/form/Extension/Validator/EventListener/ValidationListener.php line 46

  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Form\Extension\Validator\EventListener;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\Form\Extension\Validator\Constraints\Form;
  13. use Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationMapperInterface;
  14. use Symfony\Component\Form\FormEvent;
  15. use Symfony\Component\Form\FormEvents;
  16. use Symfony\Component\Validator\Validator\ValidatorInterface;
  17. /**
  18.  * @author Bernhard Schussek <bschussek@gmail.com>
  19.  */
  20. class ValidationListener implements EventSubscriberInterface
  21. {
  22.     private ValidatorInterface $validator;
  23.     private ViolationMapperInterface $violationMapper;
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [FormEvents::POST_SUBMIT => 'validateForm'];
  27.     }
  28.     public function __construct(ValidatorInterface $validatorViolationMapperInterface $violationMapper)
  29.     {
  30.         $this->validator $validator;
  31.         $this->violationMapper $violationMapper;
  32.     }
  33.     public function validateForm(FormEvent $event)
  34.     {
  35.         $form $event->getForm();
  36.         if ($form->isRoot()) {
  37.             // Form groups are validated internally (FormValidator). Here we don't set groups as they are retrieved into the validator.
  38.             foreach ($this->validator->validate($form) as $violation) {
  39.                 // Allow the "invalid" constraint to be put onto
  40.                 // non-synchronized forms
  41.                 $allowNonSynchronized $violation->getConstraint() instanceof Form && Form::NOT_SYNCHRONIZED_ERROR === $violation->getCode();
  42.                 $this->violationMapper->mapViolation($violation$form$allowNonSynchronized);
  43.             }
  44.         }
  45.     }
  46. }