Skip to content

Commit

Permalink
feat(NumberRule): remove space like a thousand delimiter
Browse files Browse the repository at this point in the history
  • Loading branch information
h4kuna committed Jan 30, 2025
1 parent 00a938f commit 1918d04
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
12 changes: 7 additions & 5 deletions src/Validation/Rules/NumberRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 10 additions & 1 deletion tests/Unit/Validation/Rules/AbstractRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
4 changes: 4 additions & 0 deletions tests/Unit/Validation/Rules/NumberRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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),
Expand Down

0 comments on commit 1918d04

Please sign in to comment.