Skip to content

Commit

Permalink
Fix backed int validation for forms.
Browse files Browse the repository at this point in the history
  • Loading branch information
dereuromark committed Mar 17, 2024
1 parent 31be06e commit b5e5c3b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/Validation/Validation.php
Expand Up @@ -808,7 +808,16 @@ public static function enum(mixed $check, string $enumClassName): bool
$backingType = null;
try {
$reflectionEnum = new ReflectionEnum($enumClassName);
$backingType = $reflectionEnum->getBackingType();

/** @var \ReflectionNamedType|\ReflectionUnionType|null $reflectionBackingType */
$reflectionBackingType = $reflectionEnum->getBackingType();
if ($reflectionBackingType) {
if (method_exists($reflectionBackingType, 'getName')) {
$backingType = $reflectionBackingType->getName();
} else {
$backingType = (string)$reflectionBackingType;
}
}
} catch (ReflectionException) {
}

Expand All @@ -818,6 +827,13 @@ public static function enum(mixed $check, string $enumClassName): bool
);
}

if ($backingType === 'int') {
if (!is_numeric($check)) {
return false;
}
$check = (int)$check;
}

if (get_debug_type($check) !== (string)$backingType) {
return false;
}
Expand Down
3 changes: 3 additions & 0 deletions tests/TestCase/Validation/ValidationTest.php
Expand Up @@ -2022,6 +2022,9 @@ public function testEnum(): void
$this->assertFalse(Validation::enum(ArticleStatus::Published, Priority::class));
$this->assertFalse(Validation::enum('wrong type', Priority::class));
$this->assertFalse(Validation::enum(123, Priority::class));

$this->assertTrue(Validation::enum('1', Priority::class));
$this->assertFalse(Validation::enum('a1', Priority::class));
}

public function testEnumNonBacked(): void
Expand Down

0 comments on commit b5e5c3b

Please sign in to comment.