Browse Source

Throw exception on misconfiguration in `Validation::enum()` too.

ndm2 2 years ago
parent
commit
d01bfb1f3e
2 changed files with 24 additions and 12 deletions
  1. 9 10
      src/Validation/Validation.php
  2. 15 2
      tests/TestCase/Validation/ValidationTest.php

+ 9 - 10
src/Validation/Validation.php

@@ -801,21 +801,20 @@ class Validation
             return true;
         }
 
-        if (
-            !is_string($check) &&
-            !is_int($check)
-        ) {
-            return false;
-        }
-
+        $backingType = null;
         try {
             $reflectionEnum = new ReflectionEnum($enumClassName);
-            $backingType = (string)$reflectionEnum->getBackingType();
+            $backingType = $reflectionEnum->getBackingType();
         } catch (ReflectionException) {
-            return false;
         }
 
-        if (get_debug_type($check) !== $backingType) {
+        if ($backingType === null) {
+            throw new InvalidArgumentException(
+                'The `$enumClassName` argument must be the classname of a valid backed enum.'
+            );
+        }
+
+        if (get_debug_type($check) !== (string)$backingType) {
             return false;
         }
 

+ 15 - 2
tests/TestCase/Validation/ValidationTest.php

@@ -2032,9 +2032,22 @@ class ValidationTest extends TestCase
         $this->assertFalse(Validation::enum(ArticleStatus::PUBLISHED, Priority::class));
         $this->assertFalse(Validation::enum('wrong type', Priority::class));
         $this->assertFalse(Validation::enum(123, Priority::class));
+    }
+
+    public function testEnumNonBacked(): void
+    {
+        $this->expectException(InvalidArgumentException::class);
+        $this->expectExceptionMessage('The `$enumClassName` argument must be the classname of a valid backed enum.');
+
+        Validation::enum(NonBacked::Basic, NonBacked::class);
+    }
+
+    public function testEnumNonEnum(): void
+    {
+        $this->expectException(InvalidArgumentException::class);
+        $this->expectExceptionMessage('The `$enumClassName` argument must be the classname of a valid backed enum.');
 
-        $this->assertFalse(Validation::enum(NonBacked::Basic, NonBacked::class));
-        $this->assertFalse(Validation::enum('non-enum class', TestCase::class));
+        Validation::enum('non-enum class', TestCase::class);
     }
 
     /**