Skip to content

[Validator] Add alpha3 option to country constraint #35116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
-----

* added the `Hostname` constraint and validator
* added option `alpha3` to `Country` constraint

5.0.0
-----
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/Constraints/Country.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function validate($value, Constraint $constraint)

$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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,55 @@ public function getInvalidCountries()
];
}

/**
* @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"
Expand Down