Skip to content

Commit

Permalink
[Validator] Check the BIC country with symfony/intl
Browse files Browse the repository at this point in the history
Fix #28167
  • Loading branch information
sylfabre committed Sep 19, 2018
1 parent 8ab7077 commit 27bd3a8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Symfony/Component/Validator/Constraints/BicValidator.php
Expand Up @@ -11,8 +11,10 @@

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Intl\Intl;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
* @author Michael Hirschler <michael.vhirsch@gmail.com>
Expand All @@ -30,6 +32,10 @@ public function validate($value, Constraint $constraint)
return;
}

if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}

$canonicalize = str_replace(' ', '', $value);

// the bic must be either 8 or 11 characters long
Expand Down Expand Up @@ -63,7 +69,11 @@ public function validate($value, Constraint $constraint)
}

// next 2 letters must be alphabetic (country code)
if (!ctype_alpha(substr($canonicalize, 4, 2))) {
if (!class_exists(Intl::class)) {
throw new \LogicException('The "symfony/intl" component is required to use the Bic constraint.');
}
$countries = Intl::getRegionBundle()->getCountryNames();
if (!isset($countries[substr($canonicalize, 4, 2)])) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(Bic::INVALID_COUNTRY_CODE_ERROR)
Expand Down
Expand Up @@ -36,6 +36,14 @@ public function testEmptyStringIsValid()
$this->assertNoViolation();
}

/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Bic());
}

/**
* @dataProvider getValidBics
*/
Expand Down Expand Up @@ -92,6 +100,7 @@ public function getInvalidBics()
array('DEUT12HH', Bic::INVALID_COUNTRY_CODE_ERROR),
array('DSBAC6BXSHA', Bic::INVALID_COUNTRY_CODE_ERROR),
array('DSBA5NBXSHA', Bic::INVALID_COUNTRY_CODE_ERROR),
array('DSBAAABXSHA', Bic::INVALID_COUNTRY_CODE_ERROR),

// branch code error
array('THISSVAL1D]', Bic::INVALID_CHARACTERS_ERROR),
Expand Down

0 comments on commit 27bd3a8

Please sign in to comment.