From f974add66afea93a6f435f161c34c9ecb60162a1 Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Mon, 2 Sep 2019 19:01:49 +0200 Subject: [PATCH] [Validator] Only handle numeric values in DivisibleBy --- .../Constraints/DivisibleByValidator.php | 10 +++++++++ .../Constraints/DivisibleByValidatorTest.php | 22 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/Symfony/Component/Validator/Constraints/DivisibleByValidator.php b/src/Symfony/Component/Validator/Constraints/DivisibleByValidator.php index a2def7f50c..53b8d38930 100644 --- a/src/Symfony/Component/Validator/Constraints/DivisibleByValidator.php +++ b/src/Symfony/Component/Validator/Constraints/DivisibleByValidator.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Validator\Constraints; +use Symfony\Component\Validator\Exception\UnexpectedValueException; + /** * Validates that values are a multiple of the given number. * @@ -23,6 +25,14 @@ class DivisibleByValidator extends AbstractComparisonValidator */ protected function compareValues($value1, $value2) { + if (!is_numeric($value1)) { + throw new UnexpectedValueException($value1, 'numeric'); + } + + if (!is_numeric($value2)) { + throw new UnexpectedValueException($value2, 'numeric'); + } + if (!$value2 = abs($value2)) { return false; } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php index e2d50574a7..99a969d51d 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php @@ -13,6 +13,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; use Symfony\Component\Validator\Constraints\DivisibleBy; use Symfony\Component\Validator\Constraints\DivisibleByValidator; +use Symfony\Component\Validator\Exception\UnexpectedValueException; /** * @author Colin O'Dell @@ -75,4 +76,25 @@ class DivisibleByValidatorTest extends AbstractComparisonValidatorTestCase ['22', '"22"', '10', '"10"', 'string'], ]; } + + /** + * @dataProvider throwsOnNonNumericValuesProvider + */ + public function testThrowsOnNonNumericValues(string $expectedGivenType, $value, $comparedValue) + { + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage(sprintf('Expected argument of type "numeric", "%s" given', $expectedGivenType)); + + $this->validator->validate($value, $this->createConstraint([ + 'value' => $comparedValue, + ])); + } + + public function throwsOnNonNumericValuesProvider() + { + return [ + [\stdClass::class, 2, new \stdClass()], + [\ArrayIterator::class, new \ArrayIterator(), 12], + ]; + } }