4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Form\Extension\Core\DataTransformer
;
14 use Symfony\Component\Form\DataTransformerInterface
;
15 use Symfony\Component\Form\Exception\TransformationFailedException
;
16 use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
;
19 * @author Bernhard Schussek <bschussek@gmail.com>
21 class ChoiceToValueTransformer
implements DataTransformerInterface
28 * @param ChoiceListInterface $choiceList
30 public function __construct(ChoiceListInterface
$choiceList)
32 $this->choiceList
= $choiceList;
35 public function transform($choice)
37 return (string) current($this->choiceList
->getValuesForChoices(array($choice)));
40 public function reverseTransform($value)
42 if (null !== $value && !is_scalar($value)) {
43 throw new TransformationFailedException('Expected a scalar.');
46 // These are now valid ChoiceList values, so we can return null
48 if ('' === $value || null === $value) {
52 $choices = $this->choiceList
->getChoicesForValues(array($value));
54 if (1 !== count($choices)) {
55 throw new TransformationFailedException(sprintf('The choice "%s" does not exist or is not unique', $value));
58 $choice = current($choices);
60 return '' === $choice ? null : $choice;