-
Notifications
You must be signed in to change notification settings - Fork 8k
Description
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.
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:
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.