ValidatorExtension.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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;
  11. use Symfony\Component\Form\AbstractExtension;
  12. use Symfony\Component\Form\Extension\Validator\Constraints\Form;
  13. use Symfony\Component\Form\FormRendererInterface;
  14. use Symfony\Component\Validator\Constraints\Traverse;
  15. use Symfony\Component\Validator\Mapping\ClassMetadata;
  16. use Symfony\Component\Validator\Validator\ValidatorInterface;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. /**
  19. * Extension supporting the Symfony Validator component in forms.
  20. *
  21. * @author Bernhard Schussek <bschussek@gmail.com>
  22. */
  23. class ValidatorExtension extends AbstractExtension
  24. {
  25. private $validator;
  26. private $formRenderer;
  27. private $translator;
  28. private $legacyErrorMessages;
  29. public function __construct(ValidatorInterface $validator, bool $legacyErrorMessages = true, FormRendererInterface $formRenderer = null, TranslatorInterface $translator = null)
  30. {
  31. $this->legacyErrorMessages = $legacyErrorMessages;
  32. $metadata = $validator->getMetadataFor('Symfony\Component\Form\Form');
  33. // Register the form constraints in the validator programmatically.
  34. // This functionality is required when using the Form component without
  35. // the DIC, where the XML file is loaded automatically. Thus the following
  36. // code must be kept synchronized with validation.xml
  37. /* @var $metadata ClassMetadata */
  38. $metadata->addConstraint(new Form());
  39. $metadata->addConstraint(new Traverse(false));
  40. $this->validator = $validator;
  41. $this->formRenderer = $formRenderer;
  42. $this->translator = $translator;
  43. }
  44. public function loadTypeGuesser()
  45. {
  46. return new ValidatorTypeGuesser($this->validator);
  47. }
  48. protected function loadTypeExtensions()
  49. {
  50. return [
  51. new Type\FormTypeValidatorExtension($this->validator, $this->legacyErrorMessages, $this->formRenderer, $this->translator),
  52. new Type\RepeatedTypeValidatorExtension(),
  53. new Type\SubmitTypeValidatorExtension(),
  54. ];
  55. }
  56. }