]>
Commit | Line | Data |
---|---|---|
4f5b44bd NL |
1 | <?php |
2 | ||
3 | /* | |
4 | * This file is part of the Symfony package. | |
5 | * | |
6 | * (c) Fabien Potencier <fabien@symfony.com> | |
7 | * | |
8 | * For the full copyright and license information, please view the LICENSE | |
9 | * file that was distributed with this source code. | |
10 | */ | |
11 | ||
12 | namespace Symfony\Component\Form\Extension\Core\DataTransformer; | |
13 | ||
14 | use Symfony\Component\Form\DataTransformerInterface; | |
15 | use Symfony\Component\Form\Exception\TransformationFailedException; | |
16 | use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface; | |
17 | ||
18 | /** | |
19 | * @author Bernhard Schussek <bschussek@gmail.com> | |
20 | */ | |
21 | class ChoiceToValueTransformer implements DataTransformerInterface | |
22 | { | |
23 | private $choiceList; | |
24 | ||
25 | /** | |
26 | * Constructor. | |
27 | * | |
28 | * @param ChoiceListInterface $choiceList | |
29 | */ | |
30 | public function __construct(ChoiceListInterface $choiceList) | |
31 | { | |
32 | $this->choiceList = $choiceList; | |
33 | } | |
34 | ||
35 | public function transform($choice) | |
36 | { | |
37 | return (string) current($this->choiceList->getValuesForChoices(array($choice))); | |
38 | } | |
39 | ||
40 | public function reverseTransform($value) | |
41 | { | |
42 | if (null !== $value && !is_scalar($value)) { | |
43 | throw new TransformationFailedException('Expected a scalar.'); | |
44 | } | |
45 | ||
46 | // These are now valid ChoiceList values, so we can return null | |
47 | // right away | |
48 | if ('' === $value || null === $value) { | |
49 | return null; | |
50 | } | |
51 | ||
52 | $choices = $this->choiceList->getChoicesForValues(array($value)); | |
53 | ||
54 | if (1 !== count($choices)) { | |
55 | throw new TransformationFailedException(sprintf('The choice "%s" does not exist or is not unique', $value)); | |
56 | } | |
57 | ||
58 | $choice = current($choices); | |
59 | ||
60 | return '' === $choice ? null : $choice; | |
61 | } | |
62 | } |