Skip to content

Commit

Permalink
[Validator] Update Type constraint, add number, finite-float an…
Browse files Browse the repository at this point in the history
…d `finite-number` validations
  • Loading branch information
guillaume-a committed Jul 13, 2023
1 parent 80f1096 commit c043d02
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* Allow single integer for the `versions` option of the `Uuid` constraint
* Allow single constraint to be passed to the `constraints` option of the `When` constraint
* Add `Finite` constraint

6.3
---
Expand Down
10 changes: 9 additions & 1 deletion src/Symfony/Component/Validator/Constraints/TypeValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ class TypeValidator extends ConstraintValidator
'float' => 'is_float',
'double' => 'is_float',
'real' => 'is_float',
'number' => 'is_int || is_float',
'finite-float' => 'is_float && is_finite',
'finite-number' => 'is_int || is_float && is_finite',
'numeric' => 'is_numeric',
'string' => 'is_string',
'scalar' => 'is_scalar',
Expand Down Expand Up @@ -69,7 +72,12 @@ public function validate(mixed $value, Constraint $constraint)

foreach ($types as $type) {
$type = strtolower($type);
if (isset(self::VALIDATION_FUNCTIONS[$type]) && self::VALIDATION_FUNCTIONS[$type]($value)) {
if (isset(self::VALIDATION_FUNCTIONS[$type]) && match ($type) {
'finite-float' => \is_float($value) && is_finite($value),
'finite-number' => \is_int($value) || \is_float($value) && is_finite($value),
'number' => \is_int($value) || \is_float($value),
default => self::VALIDATION_FUNCTIONS[$type]($value),
}) {
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@ public static function getValidValues()
['1.5', 'numeric'],
[0, 'integer'],
[1.5, 'float'],
[\NAN, 'float'],
[\INF, 'float'],
[1.5, 'finite-float'],
[0, 'number'],
[1.5, 'number'],
[\NAN, 'number'],
[\INF, 'number'],
[1.5, 'finite-number'],
['12345', 'string'],
[[], 'array'],
[$object, 'object'],
Expand Down Expand Up @@ -135,7 +143,16 @@ public static function getInvalidValues()
['foobar', 'numeric', '"foobar"'],
['foobar', 'boolean', '"foobar"'],
['0', 'integer', '"0"'],
[\NAN, 'integer', 'NAN'],
[\INF, 'integer', 'INF'],
['1.5', 'float', '"1.5"'],
['1.5', 'finite-float', '"1.5"'],
[\NAN, 'finite-float', 'NAN'],
[\INF, 'finite-float', 'INF'],
['0', 'number', '"0"'],
['0', 'finite-number', '"0"'],
[\NAN, 'finite-number', 'NAN'],
[\INF, 'finite-number', 'INF'],
[12345, 'string', '12345'],
[$object, 'boolean', 'object'],
[$object, 'numeric', 'object'],
Expand Down

0 comments on commit c043d02

Please sign in to comment.