Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
feature #35116 [Validator] Add alpha3 option to country constraint (m…
…axperrimond)

This PR was squashed before being merged into the 5.1-dev branch (closes #35116).

Discussion
----------

[Validator] Add alpha3 option to country constraint

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| Tickets       |
| License       | MIT
| Doc PR        | symfony/symfony-docs#12857

A following of #33791 and #32988 to add `alpha3` option also to `Country` constraint in the validator component.

Commits
-------

d6f34a5 [Validator] Add alpha3 option to country constraint
  • Loading branch information
fabpot committed Jan 31, 2020
2 parents 94efc95 + d6f34a5 commit 1bb485b
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
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
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
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
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

0 comments on commit 1bb485b

Please sign in to comment.