From 4765468ce6d99a1392e9554e34f8c6616fd93857 Mon Sep 17 00:00:00 2001 From: "Kouhei.Sano" Date: Fri, 13 Oct 2023 16:39:32 +0900 Subject: [PATCH 1/2] chore: Support BackedEnum --- src/ParamConverter.php | 6 ++++++ tests-php81/BackedEnumParamConverterTest.php | 17 +++++++++++++++++ tests/Fake/FakeBackedEnum.php | 9 +++++++++ 3 files changed, 32 insertions(+) create mode 100644 tests-php81/BackedEnumParamConverterTest.php create mode 100644 tests/Fake/FakeBackedEnum.php diff --git a/src/ParamConverter.php b/src/ParamConverter.php index 6eb02a4c..664f49ad 100644 --- a/src/ParamConverter.php +++ b/src/ParamConverter.php @@ -46,6 +46,12 @@ public function __invoke(array &$values): void } if (function_exists('enum_exists') && enum_exists($value::class)) { + if (method_exists($value, 'from') && method_exists($value, 'tryFrom')) { + assert(property_exists($value, 'value')); + $value = $value->value; + continue; + } + assert(property_exists($value, 'name')); $value = $value->name; continue; diff --git a/tests-php81/BackedEnumParamConverterTest.php b/tests-php81/BackedEnumParamConverterTest.php new file mode 100644 index 00000000..0f6f5362 --- /dev/null +++ b/tests-php81/BackedEnumParamConverterTest.php @@ -0,0 +1,17 @@ + FakeBackedEnum::Public]; + (new ParamConverter())($values); + $this->assertSame(['status' => 'public'], $values); + } +} diff --git a/tests/Fake/FakeBackedEnum.php b/tests/Fake/FakeBackedEnum.php new file mode 100644 index 00000000..95e11d5a --- /dev/null +++ b/tests/Fake/FakeBackedEnum.php @@ -0,0 +1,9 @@ + Date: Sat, 14 Oct 2023 13:59:01 +0900 Subject: [PATCH 2/2] refactor: Support BackedEnum --- src/ParamConverter.php | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/ParamConverter.php b/src/ParamConverter.php index 664f49ad..9aa2479c 100644 --- a/src/ParamConverter.php +++ b/src/ParamConverter.php @@ -45,19 +45,19 @@ public function __invoke(array &$values): void continue; } - if (function_exists('enum_exists') && enum_exists($value::class)) { - if (method_exists($value, 'from') && method_exists($value, 'tryFrom')) { - assert(property_exists($value, 'value')); - $value = $value->value; - continue; - } - - assert(property_exists($value, 'name')); - $value = $value->name; + $isEnumUnavailable = ! function_exists('enum_exists') || ! enum_exists($value::class); + if ($isEnumUnavailable) { + throw new CouldNotBeConvertedException(print_r($value, true)); + } + + if (method_exists($value, 'from') && method_exists($value, 'tryFrom')) { + assert(property_exists($value, 'value')); + $value = $value->value; continue; } - throw new CouldNotBeConvertedException(print_r($value, true)); + assert(property_exists($value, 'name')); + $value = $value->name; } } }