ValidatorExtensionTrait.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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\Test\Traits;
  11. use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
  12. use Symfony\Component\Form\Test\TypeTestCase;
  13. use Symfony\Component\Validator\ConstraintViolationList;
  14. use Symfony\Component\Validator\Mapping\ClassMetadata;
  15. use Symfony\Component\Validator\Validator\ValidatorInterface;
  16. trait ValidatorExtensionTrait
  17. {
  18. /**
  19. * @var ValidatorInterface|null
  20. */
  21. protected $validator;
  22. protected function getValidatorExtension(): ValidatorExtension
  23. {
  24. if (!interface_exists(ValidatorInterface::class)) {
  25. throw new \Exception('In order to use the "ValidatorExtensionTrait", the symfony/validator component must be installed.');
  26. }
  27. if (!$this instanceof TypeTestCase) {
  28. throw new \Exception(sprintf('The trait "ValidatorExtensionTrait" can only be added to a class that extends "%s".', TypeTestCase::class));
  29. }
  30. $this->validator = $this->createMock(ValidatorInterface::class);
  31. $metadata = $this->getMockBuilder(ClassMetadata::class)->setConstructorArgs([''])->setMethods(['addPropertyConstraint'])->getMock();
  32. $this->validator->expects($this->any())->method('getMetadataFor')->will($this->returnValue($metadata));
  33. $this->validator->expects($this->any())->method('validate')->will($this->returnValue(new ConstraintViolationList()));
  34. return new ValidatorExtension($this->validator, false);
  35. }
  36. }