From 27bd3a81929f502bde0fb275571ab391b9908449 Mon Sep 17 00:00:00 2001 From: Sylvain Fabre Date: Wed, 19 Sep 2018 17:27:07 +0200 Subject: [PATCH] [Validator] Check the BIC country with symfony/intl Fix #28167 --- .../Component/Validator/Constraints/BicValidator.php | 12 +++++++++++- .../Validator/Tests/Constraints/BicValidatorTest.php | 9 +++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Component/Validator/Constraints/BicValidator.php b/src/Symfony/Component/Validator/Constraints/BicValidator.php index 51aecc384ae7..da2ac5fbc382 100644 --- a/src/Symfony/Component/Validator/Constraints/BicValidator.php +++ b/src/Symfony/Component/Validator/Constraints/BicValidator.php @@ -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 @@ -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 @@ -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) diff --git a/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php index 5d21b93ced70..d135923f647a 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php @@ -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 */ @@ -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),