diff --git a/src/Symfony/Component/Validator/CHANGELOG.md b/src/Symfony/Component/Validator/CHANGELOG.md index 70e4eb432f..c5ad6222ce 100644 --- a/src/Symfony/Component/Validator/CHANGELOG.md +++ b/src/Symfony/Component/Validator/CHANGELOG.md @@ -5,6 +5,7 @@ CHANGELOG ----- * added the `Hostname` constraint and validator + * added option `alpha3` to `Country` constraint 5.0.0 ----- diff --git a/src/Symfony/Component/Validator/Constraints/Country.php b/src/Symfony/Component/Validator/Constraints/Country.php index 1eaaa985fc..1cf099c64a 100644 --- a/src/Symfony/Component/Validator/Constraints/Country.php +++ b/src/Symfony/Component/Validator/Constraints/Country.php @@ -30,6 +30,7 @@ class Country extends Constraint ]; public $message = 'This value is not a valid country.'; + public $alpha3 = false; public function __construct($options = null) { diff --git a/src/Symfony/Component/Validator/Constraints/CountryValidator.php b/src/Symfony/Component/Validator/Constraints/CountryValidator.php index acb966b270..895cca3df1 100644 --- a/src/Symfony/Component/Validator/Constraints/CountryValidator.php +++ b/src/Symfony/Component/Validator/Constraints/CountryValidator.php @@ -43,7 +43,7 @@ class CountryValidator extends ConstraintValidator $value = (string) $value; - if (!Countries::exists($value)) { + if ($constraint->alpha3 ? !Countries::alpha3CodeExists($value) : !Countries::exists($value)) { $this->context->buildViolation($constraint->message) ->setParameter('{{ value }}', $this->formatValue($value)) ->setCode(Country::NO_SUCH_COUNTRY_ERROR) diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php index 4f8ad86c5c..e46079838d 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php @@ -103,6 +103,55 @@ class CountryValidatorTest extends ConstraintValidatorTestCase ]; } + /** + * @dataProvider getValidAlpha3Countries + */ + public function testValidAlpha3Countries($country) + { + $this->validator->validate($country, new Country([ + 'alpha3' => true, + ])); + + $this->assertNoViolation(); + } + + public function getValidAlpha3Countries() + { + return [ + ['GBR'], + ['ATA'], + ['MYT'], + ]; + } + + /** + * @dataProvider getInvalidAlpha3Countries + */ + public function testInvalidAlpha3Countries($country) + { + $constraint = new Country([ + 'alpha3' => true, + 'message' => 'myMessage', + ]); + + $this->validator->validate($country, $constraint); + + $this->buildViolation('myMessage') + ->setParameter('{{ value }}', '"'.$country.'"') + ->setCode(Country::NO_SUCH_COUNTRY_ERROR) + ->assertRaised(); + } + + public function getInvalidAlpha3Countries() + { + return [ + ['foobar'], + ['GB'], + ['ZZZ'], + ['zzz'], + ]; + } + public function testValidateUsingCountrySpecificLocale() { // in order to test with "en_GB"