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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add enum_cases function #3872

Open
wants to merge 1 commit into
base: 3.x
Choose a base branch
from
Open

Conversation

HeahDude
Copy link

@HeahDude HeahDude commented Aug 22, 2023

May fix #3681.

Allows:

{% for enum in enum_cases('App\\MyBackedEnum') %}
    {{ enum.value }}
{% endfor %}

Use case:
We need to display supported locales for a language switcher in the menu.
The block is included in a header template which is included in the base. It is cumbersome to pass Locale::cases() in the context from all controllers rendering a template that inherits from the base, or to cascade the variable from template to template.

Simplified implementation:

enum Locale: string
{
    case EN = 'en';
    case FR = 'fr';

    public function flag(): string
    {
        return match ($this) {
            self::EN => '馃嚞馃嚙',
            self::FR => '馃嚝馃嚪',
        };
    }
}
{% for locale in enum_cases('App\\Locale') %}
    <option value="{{ locale.value }}"{% if locale.value == app.locale %} selected{% endif %}>
        {{ locale.flag }}
    </option>
{% endfor %}

@HeahDude
Copy link
Author

I've updated the description to show a basic use case.

public static function enumCases(string $backedEnum): array
{
if (!is_a($backedEnum, \BackedEnum::class, true)) {
throw new \InvalidArgumentException(sprintf('The enum must be a "\BackedEnum", "%s" given.', $backedEnum));
Copy link
Contributor

@GromNaN GromNaN Oct 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The restriction on BackedEnum is not necessary. As we can see in you Locale::flag example, the enum case can be used as argument to call a function, or directly to call a method on it.

}

if (80100 <= \PHP_VERSION_ID) {
enum MyBackedEnum: string
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even if you put an if around it, enum is a syntax error for PHP < 8.1. The @requires PHP 8.1 doesn't help either since the file can't be compiled on PHP 8.0 and bellow. That should be OK if you move this enum declarations in other files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

Support reading enums from PHP 8.1
2 participants