diff --git a/src/Constraint/NativeEnum.php b/src/Constraint/NativeEnum.php new file mode 100644 index 0000000..05dacc7 --- /dev/null +++ b/src/Constraint/NativeEnum.php @@ -0,0 +1,28 @@ +enumClass = $enumClass; + + $this->setErrorMessage( + $errorMessage ?? 'Invalid option for a native PHP enum. Allowed options are: ' . json_encode($this->enumClass::cases()) + ); + } + + public function validate($content): bool + { + if (!is_scalar($content)) { + return false; + } + + return !($this->enumClass::tryFrom($content) === null); + } +} diff --git a/tests/Constraint/NativeEnumTest.php b/tests/Constraint/NativeEnumTest.php new file mode 100644 index 0000000..7a93f69 --- /dev/null +++ b/tests/Constraint/NativeEnumTest.php @@ -0,0 +1,42 @@ +assertFalse($constraint->validate('test')); + $this->assertFalse($constraint->validate('blah')); + + $this->assertFalse($constraint->validate(['foo'])); + $obj = new \stdClass(); + $obj->var1 = 'foo'; + $this->assertFalse($constraint->validate($obj)); + } + + public function testIsCheckingValidData(): void + { + $constraint = new NativeEnum(FakeEnum::class); + $this->assertTrue($constraint->validate('FOO')); + $this->assertTrue($constraint->validate('BAR')); + } + + public function testIsGettingErrorMessage(): void + { + $constraint = new NativeEnum(FakeEnum::class); + $this->assertFalse($constraint->validate('test')); + $this->assertEquals('[["FOO","BAR"]] Invalid option for a native PHP enum. Allowed options are: ["FOO","BAR"]', $constraint->getErrorMessage('["FOO","BAR"]')); + } +} + +enum FakeEnum: string +{ + case Foo = 'FOO'; + case Bar = 'BAR'; +}