[Validator] Only handle numeric values in DivisibleBy

This commit is contained in:
Thomas Calvet 2019-09-02 19:01:49 +02:00
parent 61dad16c9d
commit f974add66a
2 changed files with 32 additions and 0 deletions

View File

@ -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;
}

View File

@ -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 <colinodell@gmail.com>
@ -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],
];
}
}