Skip to content
This repository has been archived by the owner on Nov 1, 2022. It is now read-only.

Commit

Permalink
Merge pull request #301 from regnerisch/main
Browse files Browse the repository at this point in the history
Adds check for enum instance when casting enums
  • Loading branch information
aidan-casey authored Sep 14, 2022
2 parents 5036b5d + 8380ad1 commit 488bef8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Casters/EnumCaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ public function __construct(

public function cast(mixed $value): mixed
{
if ($value instanceof $this->enumType) {
return $value;
}

if (! is_subclass_of($this->enumType, 'BackedEnum')) {
throw new LogicException("Caster [EnumCaster] may only be used to cast backed enums. Received [$this->enumType].");
}
Expand Down
12 changes: 12 additions & 0 deletions tests/Casters/EnumCasterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@ public function test_it_can_cast_enums(): void
$this->assertEquals(IntegerEnum::Test, $dto->integerEnum);
}

/** @test */
public function test_it_can_cast_enums_which_are_already_enums(): void
{
$dto = new EnumCastedDataTransferObject([
'integerEnum' => IntegerEnum::Test,
'stringEnum' => StringEnum::Test,
]);

$this->assertEquals(StringEnum::Test, $dto->stringEnum);
$this->assertEquals(IntegerEnum::Test, $dto->integerEnum);
}

/** @test */
public function test_it_cannot_cast_simple_enums(): void
{
Expand Down

0 comments on commit 488bef8

Please sign in to comment.