-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
Conversation
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 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. |
There was a problem hiding this 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).
@ruudk accessing a dedicated case can already be done as And returning |
Sure that might be more efficient. But if you have to repeat that multiple times with a long FQCN it looks horrible.
Since the enum is known, and this is compile time, we could compile the map like I believe it will provide for a much nicer DX being able initialize an enum as a variable using FWIW, we use a custom View codeInspired 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());
}
} |
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.
@fabpot is there anything missing before merging this PR ? |
Thank you @stof. |
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.