Skip to content

Commit 38de8a5

Browse files
author
Yann Eugoné
committed
Merge pull request #6 from yann-eugone/feature/enum-choices-as-twig-function
Added a Twig function that gives an enum choices
2 parents 63e17af + c1c06d8 commit 38de8a5

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

Tests/Twig/Extension/EnumExtensionTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,23 @@ public function testEnumLabel()
5757
);
5858
}
5959

60+
public function testEnumChoices()
61+
{
62+
$enum = $this->prophesize('EnumBundle\Enum\EnumInterface');
63+
$enum->getChoices()
64+
->willReturn(['foo' => 'FOO', 'bar' => 'BAR']);
65+
66+
$this->registry->get('test')
67+
->willReturn($enum->reveal());
68+
69+
$twig = $this->createEnvironment();
70+
71+
$this->assertSame(
72+
'foo,FOO|bar,BAR|',
73+
$twig->createTemplate("{% for value,label in enum_choices('test') %}{{ value }},{{ label }}|{% endfor %}")->render([])
74+
);
75+
}
76+
6077
/**
6178
* @return \Twig_Environment
6279
*/

Twig/Extension/EnumExtension.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ public function getFunctions()
3030
{
3131
return [
3232
new \Twig_SimpleFunction('enum_label', [ $this, 'getLabel' ]),
33+
new \Twig_SimpleFunction('enum_choices', [ $this, 'getChoices' ]),
3334
];
3435
}
3536

@@ -51,7 +52,7 @@ public function getFilters()
5152
*/
5253
public function getLabel($value, $enum)
5354
{
54-
$choices = $this->registry->get($enum)->getChoices();
55+
$choices = $this->getChoices($enum);
5556

5657
if (isset($choices[$value])) {
5758
return $choices[$value];
@@ -60,6 +61,16 @@ public function getLabel($value, $enum)
6061
return $value;
6162
}
6263

64+
/**
65+
* @param string $enum
66+
*
67+
* @return array
68+
*/
69+
public function getChoices($enum)
70+
{
71+
return $this->registry->get($enum)->getChoices();
72+
}
73+
6374
/**
6475
* {@inheritdoc}
6576
*/

0 commit comments

Comments
 (0)