datomatic / enum-helper

Simple opinionated framework agnostic PHP 8.1 enum helper

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

MyEnum::wrap()

jjjrmy opened this issue · comments

Here is an idea...

Similar to how in Laravel you can do Collection::wrap() and pass it a Collection or Array.
A function can be made similar to from() but that accepts the Enum or Backed Value.

Would you be open to accepting a PR for this?

Yes but I think is better to do that on the Laravel version of this package...
How can you implement wrap on this package?

It's not related anything to Laravel or Collections, just giving my comparison and stealing the name as I think they do the same thing. I'm open to other name suggestions.

Basically Collection::wrap() lets you pass either a Collection or Array and it returns a Collection.
Lets assume you had a function that can accept both types as a parameter.

function doSomething(Collection|array $value)
{
    return Collection::wrap($value)->pluck('color');
}

This is not possible currently with Enums, you could only do Status::from('active')
So if it was the case where you were accepting both the Backed Enum or it's String/Int value as a parameter, it is not possible without type-checking it first like:

function doSomething(Status|string $value)
{
    $enum = $value instance of Status::class ? $value : Status::from($value);
    return $enum->color();
}

This is exactly how the wrap function would work.

Status::wrap('active');
// Status::Active
Status::wrap(Status::Active);
// Status::Active
function doSomething(Status|string $value)
{
    return Status::wrap($value)->color();
}

doSomething(Status::Active);
// 'green'
doSomething('active');
// 'green'

It's basically just allowing you to use the Enum as a value with from(), which this package doesn't overload for Backed Enums.

Ok please make a PR