Skip to content

Commit

Permalink
Merge pull request #56 from rgdevment/master
Browse files Browse the repository at this point in the history
feat: add constraint for native enum
  • Loading branch information
klaussilveira authored Mar 14, 2023
2 parents 9dc0e78 + 9ae64fc commit a0ba919
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/Constraint/NativeEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Linio\Component\Input\Constraint;

class NativeEnum extends Constraint
{
protected $enumClass;

public function __construct($enumClass)
{
$this->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);
}
}
42 changes: 42 additions & 0 deletions tests/Constraint/NativeEnumTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

declare(strict_types=1);

namespace Linio\Component\Input\Constraint;

use Linio\Component\Input\TestCase;

class NativeEnumTest extends TestCase
{
public function testIsCheckingInvalidData(): void
{
$constraint = new NativeEnum(FakeEnum::class);
$this->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';
}

0 comments on commit a0ba919

Please sign in to comment.