Render backed enums using their backing value in the html_attr function

This commit is contained in:
Fabien Potencier
2026-06-25 08:50:01 +02:00
parent ec0f5d5dad
commit 9323a82eb9
3 changed files with 53 additions and 0 deletions
+1
View File
@@ -1,5 +1,6 @@
# 3.28.0 (2026-XX-XX)
* Render backed enums using their backing value in the `html_attr` function
* Fix empty Markup values being treated as truthy in and, or, xor, not, ternary, and elvis expressions
* Fix a PHP 8.5 `chr()` deprecation when decoding an octal string escape sequence larger than `\377` (such as `"\777"`)
* Mark `Twig\Markup` as `@final`; it will be final in Twig 4.0
+4
View File
@@ -200,6 +200,10 @@ final class HtmlExtension extends AbstractExtension
$runtime = $env->getRuntime(EscaperRuntime::class);
foreach ($attr as $name => $value) {
if ($value instanceof \BackedEnum) {
$value = $value->value;
}
if (str_starts_with($name, 'aria-')) {
// For aria-*, convert booleans to "true" and "false" strings
if (true === $value) {
+48
View File
@@ -247,6 +247,42 @@ class HtmlAttrTest extends TestCase
['value' => new StringableStub('stringable-object')],
],
];
// Backed enums are rendered using their backing value
yield 'string-backed enum renders its value' => [
'class="card"',
[
['class' => StringBackedStub::CARD],
],
];
yield 'int-backed enum renders its value' => [
'tabindex="10"',
[
['tabindex' => IntBackedStub::HIGH],
],
];
yield 'string-backed enum in data-* attribute renders its value without JSON encoding' => [
'data-view="card"',
[
['data-view' => StringBackedStub::CARD],
],
];
yield 'int-backed enum in data-* attribute renders its value' => [
'data-level="10"',
[
['data-level' => IntBackedStub::HIGH],
],
];
yield 'backed enum in aria-* attribute renders its value' => [
'aria-label="card"',
[
['aria-label' => StringBackedStub::CARD],
],
];
}
public function testIterableObjectCastedToArray()
@@ -317,3 +353,15 @@ class AttributeValueStub implements AttributeValueInterface
return $this->value;
}
}
enum StringBackedStub: string
{
case CARD = 'card';
case TABLE = 'table';
}
enum IntBackedStub: int
{
case LOW = 1;
case HIGH = 10;
}