From 39dfa3d724e0883663068cfc065ff400292c8fc2 Mon Sep 17 00:00:00 2001 From: Javier Spagnoletti Date: Sun, 9 Apr 2017 17:48:10 -0300 Subject: [PATCH] [Validator] Add option for LANG="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_CTYPE="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_ALL= validator --- .../Validator/Constraints/Locale.php | 1 + .../Validator/Constraints/LocaleValidator.php | 3 ++ .../Tests/Constraints/LocaleValidatorTest.php | 41 +++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/src/Symfony/Component/Validator/Constraints/Locale.php b/src/Symfony/Component/Validator/Constraints/Locale.php index 5aa7070402..0ee4bf65b8 100644 --- a/src/Symfony/Component/Validator/Constraints/Locale.php +++ b/src/Symfony/Component/Validator/Constraints/Locale.php @@ -28,4 +28,5 @@ class Locale extends Constraint ); public $message = 'This value is not a valid locale.'; + public $canonicalize = false; } diff --git a/src/Symfony/Component/Validator/Constraints/LocaleValidator.php b/src/Symfony/Component/Validator/Constraints/LocaleValidator.php index 93eab8cb7e..bf73a560c4 100644 --- a/src/Symfony/Component/Validator/Constraints/LocaleValidator.php +++ b/src/Symfony/Component/Validator/Constraints/LocaleValidator.php @@ -41,6 +41,9 @@ class LocaleValidator extends ConstraintValidator } $value = (string) $value; + if ($constraint->canonicalize) { + $value = \Locale::canonicalize($value); + } $locales = Intl::getLocaleBundle()->getLocaleNames(); $aliases = Intl::getLocaleBundle()->getAliases(); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php index 29409e61f5..7ebe1cdc8f 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php @@ -90,4 +90,45 @@ class LocaleValidatorTest extends ConstraintValidatorTestCase array('foobar'), ); } + + /** + * @dataProvider getUncanonicalizedLocales + */ + public function testInvalidLocalesWithoutCanonicalization(string $locale) + { + $constraint = new Locale(array( + 'message' => 'myMessage', + )); + + $this->validator->validate($locale, $constraint); + + $this->buildViolation('myMessage') + ->setParameter('{{ value }}', '"'.$locale.'"') + ->setCode(Locale::NO_SUCH_LOCALE_ERROR) + ->assertRaised(); + } + + /** + * @dataProvider getUncanonicalizedLocales + */ + public function testValidLocalesWithCanonicalization(string $locale) + { + $constraint = new Locale(array( + 'message' => 'myMessage', + 'canonicalize' => true, + )); + + $this->validator->validate($locale, $constraint); + + $this->assertNoViolation(); + } + + public function getUncanonicalizedLocales(): iterable + { + return array( + array('en-US'), + array('es-AR'), + array('fr_FR.utf8'), + ); + } }