diff --git a/src/Symfony/Component/Validator/ConstraintValidator.php b/src/Symfony/Component/Validator/ConstraintValidator.php index 35f41889eaee7..84d18cab396c0 100644 --- a/src/Symfony/Component/Validator/ConstraintValidator.php +++ b/src/Symfony/Component/Validator/ConstraintValidator.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Validator; use Symfony\Component\Validator\Context\ExecutionContextInterface; +use Symfony\Component\Validator\Exception\UnexpectedTypeException; /** * Base class for constraint validators. @@ -44,6 +45,40 @@ public function initialize(ExecutionContextInterface $context) $this->context = $context; } + /** + * Test a constraint class for the current validator. + * + * @throws UnexpectedTypeException + */ + final protected static function testConstraint(Constraint $constraint, string $expectedClass) + { + if (!$constraint instanceof $expectedClass) { + throw new UnexpectedTypeException($constraint, $expectedClass); + } + } + + /** + * Get a string value. + * + * @throws UnexpectedTypeException + */ + final protected static function toString($value): ?string + { + if (null === $value) { + return null; + } + + if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) { + throw new UnexpectedTypeException($value, 'string or null'); + } + + if ('' === $value = (string) $value) { + return null; + } + + return $value; + } + /** * Returns a string representation of the type of the value. * diff --git a/src/Symfony/Component/Validator/Constraints/BicValidator.php b/src/Symfony/Component/Validator/Constraints/BicValidator.php index 2d0a450e8645b..2e118161ce5ce 100644 --- a/src/Symfony/Component/Validator/Constraints/BicValidator.php +++ b/src/Symfony/Component/Validator/Constraints/BicValidator.php @@ -9,12 +9,13 @@ * file that was distributed with this source code. */ +use Symfony\Component\Validator\Constraints\Bic; + 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 @@ -28,12 +29,11 @@ class BicValidator extends ConstraintValidator */ public function validate($value, Constraint $constraint) { - if (null === $value || '' === $value) { - return; - } + /* @var Bic $constraint */ + self::testConstraint($constraint, Bic::class); - if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) { - throw new UnexpectedTypeException($value, 'string'); + if (null === $value = self::toString($value)) { + return; } $canonicalize = str_replace(' ', '', $value);