/** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setRequired('enum')->setDefault('choices_as_values', true)->setAllowedValues('enum', function ($name) { return $this->enumRegistry->has($name); })->setDefault('choices', function (Options $options) { return array_flip($this->enumRegistry->get($options['enum'])->getChoices()); }); }
/** * @param string $value * @param string $enum * * @return string */ public function getLabel($value, $enum) { $choices = $this->registry->get($enum)->getChoices(); if (isset($choices[$value])) { return $choices[$value]; } return $value; }
public function testEnumLabel() { $enum = $this->prophesize('EnumBundle\\Enum\\EnumInterface'); $enum->getChoices()->willReturn(['foo' => 'FOO', 'bar' => 'BAR']); $this->registry->get('test')->willReturn($enum->reveal()); $twig = $this->createEnvironment(); $this->assertSame('FOO', $twig->createTemplate("{{ 'foo'|enum_label('test') }}")->render([])); $this->assertSame('BAR', $twig->createTemplate("{{ enum_label('bar', 'test') }}")->render([])); $this->assertSame('not_exist', $twig->createTemplate("{{ 'not_exist'|enum_label('test') }}")->render([])); $this->assertSame('not_exist', $twig->createTemplate("{{ enum_label('not_exist', 'test') }}")->render([])); }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (!$constraint instanceof Enum) { throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\Enum'); } $constraint->choices = null; $constraint->callback = null; if (!$constraint->enum) { throw new ConstraintDefinitionException('"enum" must be specified on constraint Enum'); } if (!$this->enumRegistry->has($constraint->enum)) { throw new ConstraintDefinitionException(sprintf('"enum" "%s" on constraint Enum does not exist', $constraint->enum)); } $constraint->choices = array_keys($this->enumRegistry->get($constraint->enum)->getChoices()); parent::validate($value, $constraint); }