Skip to content

Commit

Permalink
Merge pull request #22 from 123inkt/zero-decimal-float-should-pass-in…
Browse files Browse the repository at this point in the history
…teger-constraint

a float that is forcible to int without loss of information is valid.
  • Loading branch information
frankdekker authored Aug 18, 2020
2 parents 773c4c4 + 58a9103 commit e4df1db
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 4 deletions.
6 changes: 3 additions & 3 deletions src/Constraint/Type/IntegerNumberValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ public function validate($value, Constraint $constraint): void
return;
}

// value should be either int or string
if (is_string($value) === false) {
// value should be either float or string
if (is_string($value) === false && is_float($value) === false) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode($constraint::INVALID_VALUE_TYPE)
Expand All @@ -32,7 +32,7 @@ public function validate($value, Constraint $constraint): void
}

// value can't be cast to int
if (((string)(int)$value) !== $value) {
if (((string)(int)$value) !== (string)$value) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode($constraint::INVALID_NUMBER_ERROR)
Expand Down
3 changes: 2 additions & 1 deletion tests/Unit/Constraint/Type/IntegerNumberValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use Symfony\Component\Validator\Context\ExecutionContext;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Validation;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
* @coversDefaultClass \DigitalRevolution\SymfonyValidationShorthand\Constraint\Type\IntegerNumberValidator
Expand Down Expand Up @@ -72,11 +71,13 @@ public function dataProvider(): array
'-1' => ['-1', 0],
'int 1' => [1, 0],
'int 0' => [0, 0],
'float 5.0' => [5.0, 0],
// failures
'' => ['', 1],
'a' => ['a', 1],
'0 prefix' => ['01', 1],
'true' => ['true', 1],
'float 5.5' => [5.5, 1],
'bool true' => [true, 1],
'-' => ['-', 1],
'max int' => [PHP_INT_MAX . '2', 1]
Expand Down

0 comments on commit e4df1db

Please sign in to comment.