[Validator] remove deprecated code paths

This commit is contained in:
Nicolas Grekas 2019-06-06 14:49:37 +02:00
parent 9f4dad31e2
commit 7bb0359265
17 changed files with 91 additions and 733 deletions

View File

@ -5,10 +5,13 @@ CHANGELOG
-----
* removed the `checkDNS` and `dnsMessage` options of the `Url` constraint
* removed the `checkMX`, `checkHost` and `strict` options of the `Email` constraint
* removed support for validating instances of `\DateTimeInterface` in `DateTimeValidator`, `DateValidator` and `TimeValidator`
* removed support for using the `Bic`, `Country`, `Currency`, `Language` and `Locale` constraints without `symfony/intl`
* removed support for using the `Email` constraint without `egulias/email-validator`
* removed support for using the `Expression` constraint without `symfony/expression-language`
* changed default value of `canonicalize` option of `Locale` constraint to `true`
* removed `ValidatorBuilderInterface`
4.4.0
-----

View File

@ -30,20 +30,8 @@ class Email extends Constraint
const INVALID_FORMAT_ERROR = 'bd79c0ab-ddba-46cc-a703-a7a4b08de310';
/**
* @deprecated since Symfony 4.2.
*/
const MX_CHECK_FAILED_ERROR = 'bf447c1c-0266-4e10-9c6c-573df282e413';
/**
* @deprecated since Symfony 4.2.
*/
const HOST_CHECK_FAILED_ERROR = '7da53a8b-56f3-4288-bb3e-ee9ede4ef9a1';
protected static $errorNames = [
self::INVALID_FORMAT_ERROR => 'STRICT_CHECK_FAILED_ERROR',
self::MX_CHECK_FAILED_ERROR => 'MX_CHECK_FAILED_ERROR',
self::HOST_CHECK_FAILED_ERROR => 'HOST_CHECK_FAILED_ERROR',
];
/**
@ -58,45 +46,18 @@ class Email extends Constraint
];
public $message = 'This value is not a valid email address.';
/**
* @deprecated since Symfony 4.2.
*/
public $checkMX = false;
/**
* @deprecated since Symfony 4.2.
*/
public $checkHost = false;
/**
* @deprecated since Symfony 4.1, set mode to "strict" instead.
*/
public $strict;
public $mode;
public $normalizer;
public function __construct($options = null)
{
if (\is_array($options) && \array_key_exists('strict', $options)) {
@trigger_error(sprintf('The "strict" property is deprecated since Symfony 4.1. Use "mode"=>"%s" instead.', self::VALIDATION_MODE_STRICT), E_USER_DEPRECATED);
}
if (\is_array($options) && \array_key_exists('checkMX', $options)) {
@trigger_error('The "checkMX" option is deprecated since Symfony 4.2.', E_USER_DEPRECATED);
}
if (\is_array($options) && \array_key_exists('checkHost', $options)) {
@trigger_error('The "checkHost" option is deprecated since Symfony 4.2.', E_USER_DEPRECATED);
}
if (\is_array($options) && \array_key_exists('mode', $options) && !\in_array($options['mode'], self::$validationModes, true)) {
throw new InvalidArgumentException('The "mode" parameter value is not valid.');
}
parent::__construct($options);
if ((self::VALIDATION_MODE_STRICT === $this->mode || true === $this->strict) && !class_exists(StrictEmailValidator::class)) {
if (self::VALIDATION_MODE_STRICT === $this->mode && !class_exists(StrictEmailValidator::class)) {
throw new LogicException(sprintf('The "egulias/email-validator" component is required to use the "%s" constraint in strict mode.', __CLASS__));
}

View File

@ -23,37 +23,18 @@ use Symfony\Component\Validator\Exception\UnexpectedValueException;
*/
class EmailValidator extends ConstraintValidator
{
/**
* @internal
*/
const PATTERN_HTML5 = '/^[a-zA-Z0-9.!#$%&\'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/';
/**
* @internal
*/
const PATTERN_LOOSE = '/^.+\@\S+\.\S+$/';
private const PATTERN_HTML5 = '/^[a-zA-Z0-9.!#$%&\'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/';
private const PATTERN_LOOSE = '/^.+\@\S+\.\S+$/';
private static $emailPatterns = [
Email::VALIDATION_MODE_LOOSE => self::PATTERN_LOOSE,
Email::VALIDATION_MODE_HTML5 => self::PATTERN_HTML5,
];
/**
* @var string
*/
private $defaultMode;
/**
* @param string $defaultMode
*/
public function __construct($defaultMode = Email::VALIDATION_MODE_LOOSE)
public function __construct(string $defaultMode = Email::VALIDATION_MODE_LOOSE)
{
if (\is_bool($defaultMode)) {
@trigger_error(sprintf('Calling `new %s(%s)` is deprecated since Symfony 4.1, use `new %s("%s")` instead.', self::class, $defaultMode ? 'true' : 'false', self::class, $defaultMode ? Email::VALIDATION_MODE_STRICT : Email::VALIDATION_MODE_LOOSE), E_USER_DEPRECATED);
$defaultMode = $defaultMode ? Email::VALIDATION_MODE_STRICT : Email::VALIDATION_MODE_LOOSE;
}
if (!\in_array($defaultMode, Email::$validationModes, true)) {
throw new \InvalidArgumentException('The "defaultMode" parameter value is not valid.');
}
@ -84,16 +65,6 @@ class EmailValidator extends ConstraintValidator
$value = ($constraint->normalizer)($value);
}
if (null !== $constraint->strict) {
@trigger_error(sprintf('The %s::$strict property is deprecated since Symfony 4.1. Use %s::mode="%s" instead.', Email::class, Email::class, Email::VALIDATION_MODE_STRICT), E_USER_DEPRECATED);
if ($constraint->strict) {
$constraint->mode = Email::VALIDATION_MODE_STRICT;
} else {
$constraint->mode = Email::VALIDATION_MODE_LOOSE;
}
}
if (null === $constraint->mode) {
$constraint->mode = $this->defaultMode;
}
@ -128,42 +99,5 @@ class EmailValidator extends ConstraintValidator
return;
}
$host = (string) substr($value, strrpos($value, '@') + 1);
// Check for host DNS resource records
if ($constraint->checkMX) {
if (!$this->checkMX($host)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(Email::MX_CHECK_FAILED_ERROR)
->addViolation();
}
return;
}
if ($constraint->checkHost && !$this->checkHost($host)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(Email::HOST_CHECK_FAILED_ERROR)
->addViolation();
}
}
/**
* Check DNS Records for MX type.
*/
private function checkMX(string $host): bool
{
return '' !== $host && checkdnsrr($host, 'MX');
}
/**
* Check if one of MX, A or AAAA DNS RR exists.
*/
private function checkHost(string $host): bool
{
return '' !== $host && ($this->checkMX($host) || (checkdnsrr($host, 'A') || checkdnsrr($host, 'AAAA')));
}
}

View File

@ -30,14 +30,10 @@ class Locale extends Constraint
];
public $message = 'This value is not a valid locale.';
public $canonicalize = false;
public $canonicalize = true;
public function __construct($options = null)
{
if (!($options['canonicalize'] ?? false)) {
@trigger_error('The "canonicalize" option with value "false" is deprecated since Symfony 4.1, set it to "true" instead.', E_USER_DEPRECATED);
}
if (!class_exists(Locales::class)) {
throw new LogicException('The Intl component is required to use the Locale constraint. Try running "composer require symfony/intl".');
}

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Context;
use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
@ -128,24 +127,12 @@ class ExecutionContext implements ExecutionContextInterface
private $initializedObjects;
/**
* Creates a new execution context.
* @param mixed $root The root value of the validated object graph
*
* @param ValidatorInterface $validator The validator
* @param mixed $root The root value of the
* validated object graph
* @param TranslatorInterface $translator The translator
* @param string|null $translationDomain The translation domain to
* use for translating
* violation messages
*
* @internal Called by {@link ExecutionContextFactory}. Should not be used
* in user code.
* @internal Called by {@link ExecutionContextFactory}. Should not be used in user code.
*/
public function __construct(ValidatorInterface $validator, $root, $translator, string $translationDomain = null)
public function __construct(ValidatorInterface $validator, $root, TranslatorInterface $translator, string $translationDomain = null)
{
if (!$translator instanceof LegacyTranslatorInterface && !$translator instanceof TranslatorInterface) {
throw new \TypeError(sprintf('Argument 3 passed to %s() must be an instance of %s, %s given.', __METHOD__, TranslatorInterface::class, \is_object($translator) ? \get_class($translator) : \gettype($translator)));
}
$this->validator = $validator;
$this->root = $root;
$this->translator = $translator;

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Context;
use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
@ -27,20 +26,8 @@ class ExecutionContextFactory implements ExecutionContextFactoryInterface
private $translator;
private $translationDomain;
/**
* Creates a new context factory.
*
* @param TranslatorInterface $translator The translator
* @param string|null $translationDomain The translation domain to
* use for translating
* violation messages
*/
public function __construct($translator, string $translationDomain = null)
public function __construct(TranslatorInterface $translator, string $translationDomain = null)
{
if (!$translator instanceof LegacyTranslatorInterface && !$translator instanceof TranslatorInterface) {
throw new \TypeError(sprintf('Argument 1 passed to %s() must be an instance of %s, %s given.', __METHOD__, TranslatorInterface::class, \is_object($translator) ? \get_class($translator) : \gettype($translator)));
}
$this->translator = $translator;
$this->translationDomain = $translationDomain;
}

View File

@ -11,13 +11,9 @@
namespace Symfony\Component\Validator\DependencyInjection;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface;
use Symfony\Component\Validator\Util\LegacyTranslatorProxy;
/**
* @author Fabien Potencier <fabien@symfony.com>
@ -46,33 +42,5 @@ class AddValidatorInitializersPass implements CompilerPassInterface
}
$container->getDefinition($this->builderService)->addMethodCall('addObjectInitializers', [$initializers]);
// @deprecated logic, to be removed in Symfony 5.0
$builder = $container->getDefinition($this->builderService);
$calls = [];
foreach ($builder->getMethodCalls() as list($method, $arguments)) {
if ('setTranslator' === $method) {
if (!$arguments[0] instanceof Reference) {
$translator = $arguments[0];
} elseif ($container->has($arguments[0])) {
$translator = $container->findDefinition($arguments[0]);
} else {
continue;
}
while (!($class = $translator->getClass()) && $translator instanceof ChildDefinition) {
$translator = $container->findDefinition($translator->getParent());
}
if (!is_subclass_of($class, LegacyTranslatorInterface::class)) {
$arguments[0] = (new Definition(LegacyTranslatorProxy::class))->addArgument($arguments[0]);
}
}
$calls[] = [$method, $arguments];
}
$builder->setMethodCalls($calls);
}
}

View File

@ -16,17 +16,6 @@ use Symfony\Component\Validator\Constraints\Email;
class EmailTest extends TestCase
{
/**
* @expectedDeprecation The "strict" property is deprecated since Symfony 4.1. Use "mode"=>"strict" instead.
* @group legacy
*/
public function testLegacyConstructorStrict()
{
$subject = new Email(['strict' => true]);
$this->assertTrue($subject->strict);
}
public function testConstructorStrict()
{
$subject = new Email(['mode' => Email::VALIDATION_MODE_STRICT]);

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Bridge\PhpUnit\DnsMock;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\EmailValidator;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
@ -26,19 +25,6 @@ class EmailValidatorTest extends ConstraintValidatorTestCase
return new EmailValidator(Email::VALIDATION_MODE_LOOSE);
}
/**
* @expectedDeprecation Calling `new Symfony\Component\Validator\Constraints\EmailValidator(true)` is deprecated since Symfony 4.1, use `new Symfony\Component\Validator\Constraints\EmailValidator("strict")` instead.
* @group legacy
*/
public function testLegacyValidatorConstructorStrict()
{
$this->validator = new EmailValidator(true);
$this->validator->initialize($this->context);
$this->validator->validate('example@localhost', new Email());
$this->assertNoViolation();
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The "defaultMode" parameter value is not valid.
@ -245,20 +231,6 @@ class EmailValidatorTest extends ConstraintValidatorTestCase
$this->validator->validate('example@example..com', $constraint);
}
/**
* @expectedDeprecation The "strict" property is deprecated since Symfony 4.1. Use "mode"=>"strict" instead.
* @expectedDeprecation The Symfony\Component\Validator\Constraints\Email::$strict property is deprecated since Symfony 4.1. Use Symfony\Component\Validator\Constraints\Email::mode="strict" instead.
* @group legacy
*/
public function testStrict()
{
$constraint = new Email(['strict' => true]);
$this->validator->validate('example@localhost', $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getInvalidEmailsForStrictChecks
*/
@ -333,87 +305,4 @@ class EmailValidatorTest extends ConstraintValidatorTestCase
[str_repeat('x', 254).'@example.com'], //email with warnings
];
}
/**
* @dataProvider getDnsChecks
* @requires function Symfony\Bridge\PhpUnit\DnsMock::withMockedHosts
* @group legacy
*/
public function testDnsChecks($type, $violation)
{
DnsMock::withMockedHosts(['example.com' => [['type' => $violation ? false : $type]]]);
$constraint = new Email([
'message' => 'myMessage',
'MX' === $type ? 'checkMX' : 'checkHost' => true,
]);
$this->validator->validate('foo@example.com', $constraint);
if (!$violation) {
$this->assertNoViolation();
} else {
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"foo@example.com"')
->setCode($violation)
->assertRaised();
}
}
public function getDnsChecks()
{
return [
['MX', false],
['MX', Email::MX_CHECK_FAILED_ERROR],
['A', false],
['A', Email::HOST_CHECK_FAILED_ERROR],
['AAAA', false],
['AAAA', Email::HOST_CHECK_FAILED_ERROR],
];
}
/**
* @requires function Symfony\Bridge\PhpUnit\DnsMock::withMockedHosts
* @group legacy
*/
public function testHostnameIsProperlyParsed()
{
DnsMock::withMockedHosts(['baz.com' => [['type' => 'MX']]]);
$this->validator->validate(
'"foo@bar"@baz.com',
new Email(['checkMX' => true])
);
$this->assertNoViolation();
}
/**
* @dataProvider provideCheckTypes
* @group legacy
*/
public function testEmptyHostIsNotValid($checkType, $violation)
{
$this->validator->validate(
'foo@bar.fr@',
new Email([
'message' => 'myMessage',
$checkType => true,
])
);
$this
->buildViolation('myMessage')
->setParameter('{{ value }}', '"foo@bar.fr@"')
->setCode($violation)
->assertRaised();
}
public function provideCheckTypes()
{
return [
['checkMX', Email::MX_CHECK_FAILED_ERROR],
['checkHost', Email::HOST_CHECK_FAILED_ERROR],
];
}
}

View File

@ -22,124 +22,48 @@ class LocaleValidatorTest extends ConstraintValidatorTestCase
return new LocaleValidator();
}
/**
* @group legacy
* @expectedDeprecation The "canonicalize" option with value "false" is deprecated since Symfony 4.1, set it to "true" instead.
*
* @dataProvider getValidLocales
*/
public function testLegacyNullIsValid()
public function testNullIsValid()
{
$this->validator->validate(null, new Locale());
$this->assertNoViolation();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Locale(['canonicalize' => true]));
$this->assertNoViolation();
}
/**
* @group legacy
* @expectedDeprecation The "canonicalize" option with value "false" is deprecated since Symfony 4.1, set it to "true" instead.
*
* @dataProvider getValidLocales
*/
public function testLegacyEmptyStringIsValid()
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Locale());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Locale(['canonicalize' => true]));
$this->assertNoViolation();
}
/**
* @group legacy
* @expectedDeprecation The "canonicalize" option with value "false" is deprecated since Symfony 4.1, set it to "true" instead.
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException
*/
public function testLegacyExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Locale());
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Locale(['canonicalize' => true]));
$this->validator->validate(new \stdClass(), new Locale());
}
/**
* @group legacy
* @expectedDeprecation The "canonicalize" option with value "false" is deprecated since Symfony 4.1, set it to "true" instead.
*
* @dataProvider getValidLocales
*/
public function testLegacyValidLocales(string $locale)
public function testValidLocales($locale)
{
$this->validator->validate($locale, new Locale());
$this->assertNoViolation();
}
/**
* @dataProvider getValidLocales
*/
public function testValidLocales($locale, array $options)
{
$this->validator->validate($locale, new Locale($options));
$this->assertNoViolation();
}
public function getValidLocales()
{
return [
['en', ['canonicalize' => true]],
['en_US', ['canonicalize' => true]],
['pt', ['canonicalize' => true]],
['pt_PT', ['canonicalize' => true]],
['zh_Hans', ['canonicalize' => true]],
['tl_PH', ['canonicalize' => true]],
['fil_PH', ['canonicalize' => true]], // alias for "tl_PH"
];
}
/**
* @group legacy
* @expectedDeprecation The "canonicalize" option with value "false" is deprecated since Symfony 4.1, set it to "true" instead.
* @dataProvider getLegacyInvalidLocales
*/
public function testLegacyInvalidLocales(string $locale)
{
$constraint = new Locale([
'message' => 'myMessage',
]);
$this->validator->validate($locale, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$locale.'"')
->setCode(Locale::NO_SUCH_LOCALE_ERROR)
->assertRaised();
}
public function getLegacyInvalidLocales()
{
return [
['EN'],
['foobar'],
['en'],
['en_US'],
['pt'],
['pt_PT'],
['zh_Hans'],
['tl_PH'],
['fil_PH'], // alias for "tl_PH"
];
}
@ -150,7 +74,6 @@ class LocaleValidatorTest extends ConstraintValidatorTestCase
{
$constraint = new Locale([
'message' => 'myMessage',
'canonicalize' => true,
]);
$this->validator->validate($locale, $constraint);
@ -169,25 +92,6 @@ class LocaleValidatorTest extends ConstraintValidatorTestCase
];
}
/**
* @group legacy
* @expectedDeprecation The "canonicalize" option with value "false" is deprecated since Symfony 4.1, set it to "true" instead.
* @dataProvider getUncanonicalizedLocales
*/
public function testInvalidLocalesWithoutCanonicalization(string $locale)
{
$constraint = new Locale([
'message' => 'myMessage',
]);
$this->validator->validate($locale, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$locale.'"')
->setCode(Locale::NO_SUCH_LOCALE_ERROR)
->assertRaised();
}
/**
* @dataProvider getUncanonicalizedLocales
*/
@ -195,7 +99,6 @@ class LocaleValidatorTest extends ConstraintValidatorTestCase
{
$constraint = new Locale([
'message' => 'myMessage',
'canonicalize' => true,
]);
$this->validator->validate($locale, $constraint);

View File

@ -13,13 +13,8 @@ namespace Symfony\Component\Validator\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Validator\DependencyInjection\AddValidatorInitializersPass;
use Symfony\Component\Validator\Util\LegacyTranslatorProxy;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\TranslatorTrait;
class AddValidatorInitializersPassTest extends TestCase
{
@ -46,34 +41,4 @@ class AddValidatorInitializersPassTest extends TestCase
$container->getDefinition('validator.builder')->getMethodCalls()
);
}
/**
* @group legacy
*/
public function testLegacyTranslatorProxy()
{
$translator = new TestTranslator();
$proxy = new LegacyTranslatorProxy($translator);
$this->assertSame($translator, $proxy->getTranslator());
$container = new ContainerBuilder();
$container
->register('validator.builder')
->addMethodCall('setTranslator', [new Reference('translator')])
;
$container->register('translator', TestTranslator::class);
(new AddValidatorInitializersPass())->process($container);
$this->assertEquals(
[['setTranslator', [(new Definition(LegacyTranslatorProxy::class))->addArgument(new Reference('translator'))]]],
$container->getDefinition('validator.builder')->removeMethodCall('addObjectInitializers')->getMethodCalls()
);
}
}
class TestTranslator implements TranslatorInterface, LocaleAwareInterface
{
use TranslatorTrait;
}

View File

@ -12,14 +12,12 @@
namespace Symfony\Component\Validator\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Util\LegacyTranslatorProxy;
use Symfony\Component\Validator\ValidatorBuilder;
use Symfony\Component\Validator\ValidatorBuilderInterface;
class ValidatorBuilderTest extends TestCase
{
/**
* @var ValidatorBuilderInterface
* @var ValidatorBuilder
*/
protected $builder;
@ -102,18 +100,10 @@ class ValidatorBuilderTest extends TestCase
public function testSetTranslator()
{
$this->assertSame($this->builder, $this->builder->setTranslator(
$this->getMockBuilder('Symfony\Component\Translation\TranslatorInterface')->getMock())
$this->getMockBuilder('Symfony\Contracts\Translation\TranslatorInterface')->getMock())
);
}
public function testLegacyTranslatorProxy()
{
$proxy = $this->getMockBuilder(LegacyTranslatorProxy::class)->disableOriginalConstructor()->getMock();
$proxy->expects($this->once())->method('getTranslator');
$this->builder->setTranslator($proxy);
}
public function testSetTranslationDomain()
{
$this->assertSame($this->builder, $this->builder->setTranslationDomain('TRANS_DOMAIN'));

View File

@ -1,80 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Util;
use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* @internal to be removed in Symfony 5.0.
*/
class LegacyTranslatorProxy implements LegacyTranslatorInterface, TranslatorInterface
{
private $translator;
/**
* @param LegacyTranslatorInterface|TranslatorInterface $translator
*/
public function __construct($translator)
{
if ($translator instanceof LegacyTranslatorInterface) {
// no-op
} elseif (!$translator instanceof TranslatorInterface) {
throw new \InvalidArgumentException(sprintf('The translator passed to "%s()" must implement "%s" or "%s".', __METHOD__, TranslatorInterface::class, LegacyTranslatorInterface::class));
} elseif (!$translator instanceof LocaleAwareInterface) {
throw new \InvalidArgumentException(sprintf('The translator passed to "%s()" must implement "%s".', __METHOD__, LocaleAwareInterface::class));
}
$this->translator = $translator;
}
/**
* @return LegacyTranslatorInterface|TranslatorInterface
*/
public function getTranslator()
{
return $this->translator;
}
/**
* {@inheritdoc}
*/
public function setLocale($locale)
{
$this->translator->setLocale($locale);
}
/**
* {@inheritdoc}
*/
public function getLocale()
{
return $this->translator->getLocale();
}
/**
* {@inheritdoc}
*/
public function trans($id, array $parameters = [], $domain = null, $locale = null)
{
return $this->translator->trans($id, $parameters, $domain, $locale);
}
/**
* {@inheritdoc}
*/
public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null)
{
return $this->translator->trans($id, ['%count%' => $number] + $parameters, $domain, $locale);
}
}

View File

@ -25,19 +25,12 @@ final class Validation
*
* If you want to configure the validator, use
* {@link createValidatorBuilder()} instead.
*
* @return ValidatorInterface The new validator
*/
public static function createValidator(): ValidatorInterface
{
return self::createValidatorBuilder()->getValidator();
}
/**
* Creates a configurable builder for validator objects.
*
* @return ValidatorBuilderInterface The new builder
*/
public static function createValidatorBuilder(): ValidatorBuilder
{
return new ValidatorBuilder();

View File

@ -15,7 +15,6 @@ use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Annotations\Reader;
use Doctrine\Common\Cache\ArrayCache;
use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface;
use Symfony\Component\Validator\Context\ExecutionContextFactory;
use Symfony\Component\Validator\Exception\LogicException;
use Symfony\Component\Validator\Exception\ValidatorException;
@ -28,20 +27,16 @@ use Symfony\Component\Validator\Mapping\Loader\LoaderInterface;
use Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader;
use Symfony\Component\Validator\Mapping\Loader\XmlFileLoader;
use Symfony\Component\Validator\Mapping\Loader\YamlFileLoader;
use Symfony\Component\Validator\Util\LegacyTranslatorProxy;
use Symfony\Component\Validator\Validator\RecursiveValidator;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\TranslatorTrait;
/**
* The default implementation of {@link ValidatorBuilderInterface}.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @final since Symfony 4.2
*/
class ValidatorBuilder implements ValidatorBuilderInterface
class ValidatorBuilder
{
private $initializers = [];
private $loaders = [];
@ -80,7 +75,9 @@ class ValidatorBuilder implements ValidatorBuilderInterface
private $translationDomain;
/**
* {@inheritdoc}
* Adds an object initializer to the validator.
*
* @return $this
*/
public function addObjectInitializer(ObjectInitializerInterface $initializer)
{
@ -90,7 +87,11 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Adds a list of object initializers to the validator.
*
* @param ObjectInitializerInterface[] $initializers
*
* @return $this
*/
public function addObjectInitializers(array $initializers)
{
@ -100,7 +101,9 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Adds an XML constraint mapping file to the validator.
*
* @return $this
*/
public function addXmlMapping($path)
{
@ -114,7 +117,11 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Adds a list of XML constraint mapping files to the validator.
*
* @param string[] $paths The paths to the mapping files
*
* @return $this
*/
public function addXmlMappings(array $paths)
{
@ -128,7 +135,11 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Adds a YAML constraint mapping file to the validator.
*
* @param string $path The path to the mapping file
*
* @return $this
*/
public function addYamlMapping($path)
{
@ -142,7 +153,11 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Adds a list of YAML constraint mappings file to the validator.
*
* @param string[] $paths The paths to the mapping files
*
* @return $this
*/
public function addYamlMappings(array $paths)
{
@ -156,7 +171,9 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Enables constraint mapping using the given static method.
*
* @return $this
*/
public function addMethodMapping($methodName)
{
@ -170,7 +187,11 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Enables constraint mapping using the given static methods.
*
* @param string[] $methodNames The names of the methods
*
* @return $this
*/
public function addMethodMappings(array $methodNames)
{
@ -184,7 +205,9 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Enables annotation based constraint mapping.
*
* @return $this
*/
public function enableAnnotationMapping(Reader $annotationReader = null)
{
@ -206,7 +229,9 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Disables annotation based constraint mapping.
*
* @return $this
*/
public function disableAnnotationMapping()
{
@ -216,7 +241,9 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Sets the class metadata factory used by the validator.
*
* @return $this
*/
public function setMetadataFactory(MetadataFactoryInterface $metadataFactory)
{
@ -230,7 +257,9 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Sets the cache for caching class metadata.
*
* @return $this
*/
public function setMetadataCache(CacheInterface $cache)
{
@ -244,7 +273,9 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Sets the constraint validator factory used by the validator.
*
* @return $this
*/
public function setConstraintValidatorFactory(ConstraintValidatorFactoryInterface $validatorFactory)
{
@ -254,21 +285,25 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Sets the translator used for translating violation messages.
*
* @return $this
*/
public function setTranslator(LegacyTranslatorInterface $translator)
public function setTranslator(TranslatorInterface $translator)
{
$this->translator = $translator;
while ($this->translator instanceof LegacyTranslatorProxy) {
$this->translator = $this->translator->getTranslator();
}
return $this;
}
/**
* {@inheritdoc}
* Sets the default translation domain of violation messages.
*
* The same message can have different translations in different domains.
* Pass the domain that is used for violation messages by default to this
* method.
*
* @return $this
*/
public function setTranslationDomain($translationDomain)
{
@ -314,7 +349,9 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
/**
* {@inheritdoc}
* Builds and returns a new validator object.
*
* @return ValidatorInterface
*/
public function getValidator()
{

View File

@ -1,160 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator;
use Doctrine\Common\Annotations\Reader;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Mapping\Cache\CacheInterface;
use Symfony\Component\Validator\Mapping\Factory\MetadataFactoryInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* A configurable builder for ValidatorInterface objects.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated since Symfony 4.2, use the ValidatorBuilder class instead
*/
interface ValidatorBuilderInterface
{
/**
* Adds an object initializer to the validator.
*
* @return $this
*/
public function addObjectInitializer(ObjectInitializerInterface $initializer);
/**
* Adds a list of object initializers to the validator.
*
* @param ObjectInitializerInterface[] $initializers
*
* @return $this
*/
public function addObjectInitializers(array $initializers);
/**
* Adds an XML constraint mapping file to the validator.
*
* @param string $path The path to the mapping file
*
* @return $this
*/
public function addXmlMapping($path);
/**
* Adds a list of XML constraint mapping files to the validator.
*
* @param string[] $paths The paths to the mapping files
*
* @return $this
*/
public function addXmlMappings(array $paths);
/**
* Adds a YAML constraint mapping file to the validator.
*
* @param string $path The path to the mapping file
*
* @return $this
*/
public function addYamlMapping($path);
/**
* Adds a list of YAML constraint mappings file to the validator.
*
* @param string[] $paths The paths to the mapping files
*
* @return $this
*/
public function addYamlMappings(array $paths);
/**
* Enables constraint mapping using the given static method.
*
* @param string $methodName The name of the method
*
* @return $this
*/
public function addMethodMapping($methodName);
/**
* Enables constraint mapping using the given static methods.
*
* @param string[] $methodNames The names of the methods
*
* @return $this
*/
public function addMethodMappings(array $methodNames);
/**
* Enables annotation based constraint mapping.
*
* @return $this
*/
public function enableAnnotationMapping(Reader $annotationReader = null);
/**
* Disables annotation based constraint mapping.
*
* @return $this
*/
public function disableAnnotationMapping();
/**
* Sets the class metadata factory used by the validator.
*
* @return $this
*/
public function setMetadataFactory(MetadataFactoryInterface $metadataFactory);
/**
* Sets the cache for caching class metadata.
*
* @return $this
*/
public function setMetadataCache(CacheInterface $cache);
/**
* Sets the constraint validator factory used by the validator.
*
* @return $this
*/
public function setConstraintValidatorFactory(ConstraintValidatorFactoryInterface $validatorFactory);
/**
* Sets the translator used for translating violation messages.
*
* @return $this
*/
public function setTranslator(TranslatorInterface $translator);
/**
* Sets the default translation domain of violation messages.
*
* The same message can have different translations in different domains.
* Pass the domain that is used for violation messages by default to this
* method.
*
* @param string $translationDomain The translation domain of the violation messages
*
* @return $this
*/
public function setTranslationDomain($translationDomain);
/**
* Builds and returns a new validator object.
*
* @return ValidatorInterface The built validator
*/
public function getValidator();
}

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Violation;
use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
@ -47,11 +46,8 @@ class ConstraintViolationBuilder implements ConstraintViolationBuilderInterface
/**
* @param TranslatorInterface $translator
*/
public function __construct(ConstraintViolationList $violations, Constraint $constraint, $message, array $parameters, $root, $propertyPath, $invalidValue, $translator, $translationDomain = null)
public function __construct(ConstraintViolationList $violations, Constraint $constraint, $message, array $parameters, $root, $propertyPath, $invalidValue, TranslatorInterface $translator, $translationDomain = null)
{
if (!$translator instanceof LegacyTranslatorInterface && !$translator instanceof TranslatorInterface) {
throw new \TypeError(sprintf('Argument 8 passed to %s() must be an instance of %s, %s given.', __METHOD__, TranslatorInterface::class, \is_object($translator) ? \get_class($translator) : \gettype($translator)));
}
$this->violations = $violations;
$this->message = $message;
$this->parameters = $parameters;