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

Implement the enum_cases function #4177

Merged
merged 1 commit into from
Aug 10, 2024
Merged

Implement the enum_cases function #4177

merged 1 commit into from
Aug 10, 2024

Conversation

stof
Copy link
Member

@stof stof commented Aug 7, 2024

The implementation contains an optimized implementation of the function for the common case of using a string literal as the argument. It will validate the enum existence during compilation and compile the code to use MyEnum::cases() directly.

Closes #3872 (it replaces it)
Relates to #3681 (it solves the case of getting the list of cases)

Note that the strict compile time validation for string literals is especially beneficial as long as escaping \ is mandatory in our string literals (where escaping non-special characters is the same than not putting the backslash) as by experience, this is a common mistake when trying to put a PHP FQCN in a Twig string. One of the tests I added is covering exactly this kind of mistake.

@stof
Copy link
Member Author

stof commented Aug 7, 2024

The compile-time check has 1 drawback though: it means that a template will fail to compile even if the usage of the enum is inside a {% if %} where the runtime check would ensure existence of the enum coming from an optional dependency.

When I implemented this logic in the Incenteev codebase, this drawback was not present (in a project, this case of optional dependencies does not exist) and so I favored the benefit of getting a compile-time error for invalid class name, especially because of the escaping requirement of Twig.
If we ship the deprecation of no-op escaping in string literals, this would at least report a deprecation warning for the escaping mistake, which might make it fine to change the behavior for other kind of errors to a runtime error instead.

Copy link
Contributor

@ruudk ruudk left a comment

Choose a reason for hiding this comment

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

Currently enum_cases('FQCN') returns a list<UnitEnum>.

Wouldn't it be better to return array<string, UnitEnum> instead? Where the key is the enum case name.

This would allow things like

{% if order.status == enum_cases('App\\Status').Paid %}
{% set enum = enum_cases('App\\Status') %}
{% if order.status == enum.Paid %}

If I look at our large codebase, we often want to compare if a returned enum from an entity is equal to our expectation. Getting a list of enum cases is rarely used (but could still be handy sometimes).

@stof
Copy link
Member Author

stof commented Aug 8, 2024

@ruudk accessing a dedicated case can already be done as constant('App\\Status::PAID') in a much more efficient way.

And returning array<string, UnitEnum> would require dropping the optimization compiling directly to App\Status::cases() when the enum is known at compile time.

@stof
Copy link
Member Author

stof commented Aug 8, 2024

@ruudk the use case for getting a list of enums is creating a selector between cases (for instance a language selector as done in the example in #3872). I have lots of such cases in my project (which is why I implemented it there first before contributing it to Twig)

@ruudk
Copy link
Contributor

ruudk commented Aug 8, 2024

accessing a dedicated case can already be done as constant('App\\Status::PAID') in a much more efficient way

Sure that might be more efficient. But if you have to repeat that multiple times with a long FQCN it looks horrible.

And returning array<string, UnitEnum> would require dropping the optimization compiling directly to App\Status::cases() when the enum is known at compile time.

Since the enum is known, and this is compile time, we could compile the map like ['Paid' => App\Status::Paid, ....].

I believe it will provide for a much nicer DX being able initialize an enum as a variable using {% set enum = enum_cases('App\\Status') %} and then reference it in all the conditions using {% if order.status == enum.Paid %}.

FWIW, we use a custom enum function in our codebase that works like this:

View code

Inspired by #3681 (comment)

{% set myEnum = enum('App\MyEnum') %}
{% if someValue == myEnum.someCase %}
    Match!
{% endif %}
{% for case in myEnum %}
  Hello {{ case.name }} = {{ case.value }}
{% endfor %}
use Override;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use UnitEnum;
final class EnumExtension extends AbstractExtension
{
    #[Override]
    public function getFunctions() : array
    {
        return [
            new TwigFunction('enum', $this->enum(...)),
        ];
    }

    /**
     * @template T of UnitEnum
     * @param class-string<T> $enum
     *
     * @return EnumProxy<T>
     */
    public function enum(string $enum) : EnumProxy
    {
        return new EnumProxy($enum);
    }
}
use ArrayIterator;
use BackedEnum;
use BadMethodCallException;
use IteratorAggregate;
use Override;
use TicketSwap\Shared\Infrastructure\Helper\AssertReturn;
use UnitEnum;
use Webmozart\Assert\Assert;
/**
 * @template T of UnitEnum
 * @method T from(string $value)
 * @method null|T tryFrom(string $value)
 * @implements IteratorAggregate<int, T>
 */
final readonly class EnumProxy implements IteratorAggregate
{
    /**
     * @param class-string<T> $enum
     */
    public function __construct(
        private string $enum,
    ) {
        Assert::true(enum_exists($enum), 'Enum class "%s" does not exist.');
    }

    /**
     * @param array<mixed> $arguments
     *
     * @return null|T
     */
    public function __call(string $name, array $arguments)
    {
        $fqcn = sprintf('%s::%s', $this->enum, $name);

        if (defined($fqcn)) {
            return AssertReturn::instanceOf(constant($fqcn), $this->enum);
        }

        if (is_a($this->enum, BackedEnum::class, true)) {
            if ($name === 'from') {
                return AssertReturn::instanceOf(forward_static_call([$this->enum, $name], ...$arguments), $this->enum);
            }

            if ($name === 'tryFrom') {
                return AssertReturn::nullOrInstanceOf(forward_static_call([$this->enum, $name], ...$arguments), $this->enum);
            }
        }

        throw new BadMethodCallException(sprintf('Enum "%s" does not have a case "%s".', $this->enum, $name));
    }

    /**
     * @return ArrayIterator<int, T>
     */
    #[Override]
    public function getIterator() : ArrayIterator
    {
        return new ArrayIterator($this->enum::cases());
    }
}

@stof
Copy link
Member Author

stof commented Aug 8, 2024

Since the enum is known, and this is compile time, we could compile the map like ['Paid' => App\Status::Paid, ....].

this would imply that a template has to be recompiled when the enum is modified to add a new case, which would not happen automatically with auto_reload.

The implementation contains an optimized implementation of the function
for the common case of using a string literal as the argument. It will
validate the enum existence during compilation and compile the code to
use `MyEnum::cases()` directly.
@stof
Copy link
Member Author

stof commented Aug 9, 2024

@fabpot is there anything missing before merging this PR ?

@fabpot
Copy link
Contributor

fabpot commented Aug 10, 2024

Thank you @stof.

@fabpot fabpot merged commit aed4990 into twigphp:3.x Aug 10, 2024
75 of 76 checks passed
@stof stof deleted the enum_cases branch August 12, 2024 07:13
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.

3 participants