Skip to content

Commit

Permalink
Merge pull request #52 from apple-x-co/backed-enum
Browse files Browse the repository at this point in the history
Add ParamConverter supports BackedEnum
  • Loading branch information
koriym authored Oct 14, 2023
2 parents e38a4a3 + 3a3ba9d commit 02ad56d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/ParamConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,19 @@ public function __invoke(array &$values): void
continue;
}

if (function_exists('enum_exists') && enum_exists($value::class)) {
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;
}
}
}
17 changes: 17 additions & 0 deletions tests-php81/BackedEnumParamConverterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Ray\MediaQuery;

use PHPUnit\Framework\TestCase;

class BackedEnumParamConverterTest extends TestCase
{
public function testInvoke(): void
{
$values = ['status' => FakeBackedEnum::Public];
(new ParamConverter())($values);
$this->assertSame(['status' => 'public'], $values);
}
}
9 changes: 9 additions & 0 deletions tests/Fake/FakeBackedEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Ray\MediaQuery;

enum FakeBackedEnum: string
{
case Draft = 'draft';
case Public = 'public';
}

0 comments on commit 02ad56d

Please sign in to comment.