bug #33435 [Validator] Only handle numeric values in DivisibleBy (fancyweb)

This PR was merged into the 4.3 branch.

Discussion
----------

[Validator] Only handle numeric values in DivisibleBy

| Q             | A
| ------------- | ---
| Branch?       | 4.3
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | -

Currently it probably breaks because `abs` throws a notice on objects.

Commits
-------

f974add66a [Validator] Only handle numeric values in DivisibleBy
This commit is contained in:
Fabien Potencier 2019-09-03 18:22:42 +02:00
commit c0f4037769
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],
];
}
}