Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map by name=>value #57

Closed
dionysiosarvanitis opened this issue Jun 26, 2020 · 6 comments · Fixed by #58
Closed

Map by name=>value #57

dionysiosarvanitis opened this issue Jun 26, 2020 · 6 comments · Fixed by #58
Assignees
Labels
question Further information is requested

Comments

@dionysiosarvanitis
Copy link

dionysiosarvanitis commented Jun 26, 2020

Hi, is there any way to get something like below:

class SaveStatus extends Enum
{
    public static function toArray(): array
    {
        return array_combine(static::getNames(), static::getValues());
    }
}

I use names instead of indexes so the mapping should be name=>value

@Gummibeer
Copy link
Collaborator

Hey,

you've already posted the solution. Just put this into your own base Enum class and extend this with all your enums.

namespace App\Enums;

abstract class Enum extends \Spatie\Enum\Enum
{
    public static function toArray(): array
    {
        return array_combine(static::getNames(), static::getValues());
    }
}

final class SaveStatus extends \App\Enums\Enum {}

@Gummibeer Gummibeer added the question Further information is requested label Jun 29, 2020
@Gummibeer Gummibeer self-assigned this Jun 29, 2020
@dionysiosarvanitis
Copy link
Author

Hi! Thank you for answering.

I tried what you said, but I got error on initialization. Constructor's 3rd argument $index must be an int. Overriding it is not enough because getIndex() must also return int.

public function __construct(?string $name = null, ?string $value = null, ?int $index = null)

self::$cache[$class][$name]['index'] = static::make($name)->getIndex();

@Gummibeer
Copy link
Collaborator

Good point, right now we depend on the toArray() method in resolve logic.
This should be changed. I think that this is changed by @brendt in v3 #56
For the moment you could add your own method to achieve what you need.

Gummibeer added a commit that referenced this issue Jun 29, 2020
@Gummibeer
Copy link
Collaborator

@dionysiosarvanitis I've added a PR #58 that drops the usage of toArray() in the Enum class itself.

@Gummibeer
Copy link
Collaborator

@dionysiosarvanitis
Copy link
Author

Works great. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants