From 1918d045a183c31bc8fd756a9a71008752f50e7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milan=20Mat=C4=9Bj=C4=8Dek?= Date: Thu, 30 Jan 2025 09:12:51 +0100 Subject: [PATCH] feat(NumberRule): remove space like a thousand delimiter --- src/Validation/Rules/NumberRule.php | 12 +++++++----- tests/Unit/Validation/Rules/AbstractRuleTest.php | 11 ++++++++++- tests/Unit/Validation/Rules/NumberRuleTest.php | 4 ++++ 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/Validation/Rules/NumberRule.php b/src/Validation/Rules/NumberRule.php index d6644508..9223de84 100644 --- a/src/Validation/Rules/NumberRule.php +++ b/src/Validation/Rules/NumberRule.php @@ -11,18 +11,20 @@ class NumberRule implements Rule { public function passes($attribute, $value): bool { + if (is_string($value)) { + $value = preg_replace('#\s+#', '', $value); + } + if (self::isNumericInt($value)) { $intVal = (int) $value; return $intVal !== PHP_INT_MAX && $intVal !== PHP_INT_MIN; + } elseif (is_scalar($value) === false) { + return false; } $value = Value::toFloat((string) $value); - if ($value === null) { - return false; - } - - return str_contains((string) $value, 'E+') === false; + return $value !== null && (str_contains((string) $value, 'E+') === false); } public function message(): string diff --git a/tests/Unit/Validation/Rules/AbstractRuleTest.php b/tests/Unit/Validation/Rules/AbstractRuleTest.php index 2bd15715..568b5ad7 100644 --- a/tests/Unit/Validation/Rules/AbstractRuleTest.php +++ b/tests/Unit/Validation/Rules/AbstractRuleTest.php @@ -39,9 +39,18 @@ protected function testPassesData(): array { $data = []; foreach ($this->testData() as $index => $entity) { - $data[$index . ' with value: ' . $entity->value] = [$entity]; + $data[$index . ' with value: ' . self::convertToString($entity->value)] = [$entity]; } return $data; } + + private static function convertToString(mixed $value): string + { + if (is_array($value)) { + return 'array'; + } + + return (string) $value; + } } diff --git a/tests/Unit/Validation/Rules/NumberRuleTest.php b/tests/Unit/Validation/Rules/NumberRuleTest.php index 65cecd35..7f15f27f 100644 --- a/tests/Unit/Validation/Rules/NumberRuleTest.php +++ b/tests/Unit/Validation/Rules/NumberRuleTest.php @@ -19,6 +19,8 @@ protected function testData(): array return [ new RuleExpectation('test', false), new RuleExpectation('234', true), + new RuleExpectation(" - 1\t234. 065 ", true), + new RuleExpectation(' 1 234. 065 ', true), new RuleExpectation('-234', true), new RuleExpectation(234, true), new RuleExpectation(-234, true), @@ -47,6 +49,8 @@ protected function testData(): array new RuleExpectation('-,', false), new RuleExpectation('.', false), new RuleExpectation('', false), + new RuleExpectation(null, false), + new RuleExpectation([], false), new RuleExpectation('9223372036854775807', false), new RuleExpectation('9223372036854775807.5', false), new RuleExpectation('922337203685477580703434355.5', false),