[Validator] Add alpha3 option to country constraint

This commit is contained in:
maxime.perrimond 2019-12-27 14:33:21 +09:00 committed by Fabien Potencier
parent 81abb4e156
commit d6f34a5df6
4 changed files with 52 additions and 1 deletions

View File

@ -5,6 +5,7 @@ CHANGELOG
-----
* added the `Hostname` constraint and validator
* added option `alpha3` to `Country` constraint
5.0.0
-----

View File

@ -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)
{

View File

@ -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)

View File

@ -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"