From 0bf01a3beaf72a452599a5f18830cbb8643dd206 Mon Sep 17 00:00:00 2001 From: sean Date: Tue, 14 May 2024 01:05:28 +0800 Subject: [PATCH] it can create data when enum is already casted --- src/Casts/EnumCast.php | 2 +- tests/Casts/EnumCastTest.php | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/Casts/EnumCast.php b/src/Casts/EnumCast.php index fa3cde72e..c0cc4b4a7 100644 --- a/src/Casts/EnumCast.php +++ b/src/Casts/EnumCast.php @@ -38,7 +38,7 @@ protected function castValue( /** @var class-string<\BackedEnum> $type */ try { - return $type::from($value); + return $value instanceof $type && $value === $type::from($value->value) ? $value : $type::from($value); } catch (Throwable $e) { throw CannotCastEnum::create($type, $value); } diff --git a/tests/Casts/EnumCastTest.php b/tests/Casts/EnumCastTest.php index 219fca57c..cc54c79c4 100644 --- a/tests/Casts/EnumCastTest.php +++ b/tests/Casts/EnumCastTest.php @@ -71,3 +71,19 @@ ) ->toEqual(Uncastable::create()); }); + + +it('it can create data when enum is already casted', function () { + $class = new class () { + public DummyBackedEnum $enum; + }; + + expect( + $this->caster->cast( + FakeDataStructureFactory::property($class, 'enum'), + DummyBackedEnum::FOO, + [], + CreationContextFactory::createFromConfig($class::class)->get() + ) + )->toEqual(DummyBackedEnum::FOO); +});