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

allow enum casting not only enum value casting #301

Merged
merged 1 commit into from
Sep 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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