[php-src] Issue #9352: Retrieving an enum case by its name
| From: | ollieread | Date: | Tue, 16 Aug 2022 15:57:12 +0000 |
| Subject: | [php-src] Issue #9352: Retrieving an enum case by its name | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-242231@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/9352
Author: ollieread
### Description
I'm proposing that we add two new methods to the
UnitEnum interface,
named and tryNamed, which exist as the counterparts for
BackedEnum::from and BackeEnum::tryFrom, but use the enum name. I believe
this would allow developers to avoid arbitrarily creating backed enums where the name will do,
without writing unnecessary userland code to retrieve a case given its name.
## Reasoning
We currently have the from and tryFrom methods for retrieving backed enums
based on their values, but we have no way to retrieve an enum case using its name.
There are two possible ways to solve this in userland.
The first is to make the enum backed, but that can introduce unnecessary code. Take the following
Status enum.
```php
enum Status: string {
case Todo = 'todo';
case InProgress = 'inprogress';
case InReview = 'inreview';
case Done = 'done';
}
```
While not super complex, the string value is entirely unnecessary, as it's just a lowercase
version of the name.
The second solution is to store $enum->name and then retrieve the case by doing
something like the following:
```php
foreach (Status::cases() as $case) {
if ($case->name === $name) {
return $case;
}
}
```
There is probably a more efficient way of doing this, but I think this accurately portrays what I
mean.
While not hugely complex, each of these solutions requires the writing of unnecessary code for
something that should be easily achieved.