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\Extension\Core\ChoiceList\ChoiceListInterface
;
15 use Symfony\Component\Form\DataTransformerInterface
;
16 use Symfony\Component\Form\Exception\TransformationFailedException
;
19 * @author Bernhard Schussek <bschussek@gmail.com>
21 class ChoicesToBooleanArrayTransformer
implements DataTransformerInterface
25 public function __construct(ChoiceListInterface
$choiceList)
27 $this->choiceList
= $choiceList;
31 * Transforms an array of choices to a format appropriate for the nested
32 * checkboxes/radio buttons.
34 * The result is an array with the options as keys and true/false as values,
35 * depending on whether a given option is selected. If this field is rendered
36 * as select tag, the value is not modified.
38 * @param mixed $array An array
40 * @return mixed An array
42 * @throws TransformationFailedException If the given value is not an array
43 * or if the choices can not be retrieved.
45 public function transform($array)
47 if (null === $array) {
51 if (!is_array($array)) {
52 throw new TransformationFailedException('Expected an array.');
56 $values = $this->choiceList
->getValues();
57 } catch (\Exception
$e) {
58 throw new TransformationFailedException('Can not get the choice list', $e->getCode(), $e);
61 $indexMap = array_flip($this->choiceList
->getIndicesForChoices($array));
63 foreach ($values as $i => $value) {
64 $values[$i] = isset($indexMap[$i]);
71 * Transforms a checkbox/radio button array to an array of choices.
73 * The input value is an array with the choices as keys and true/false as
74 * values, depending on whether a given choice is selected. The output
75 * is an array with the selected choices.
77 * @param mixed $values An array
79 * @return mixed An array
81 * @throws TransformationFailedException If the given value is not an array,
82 * if the recuperation of the choices
83 * fails or if some choice can't be
86 public function reverseTransform($values)
88 if (!is_array($values)) {
89 throw new TransformationFailedException('Expected an array.');
93 $choices = $this->choiceList
->getChoices();
94 } catch (\Exception
$e) {
95 throw new TransformationFailedException('Can not get the choice list', $e->getCode(), $e);
101 foreach ($values as $i => $selected) {
103 if (isset($choices[$i])) {
104 $result[] = $choices[$i];
111 if (count($unknown) > 0) {
112 throw new TransformationFailedException(sprintf('The choices "%s" were not found', implode('", "', $unknown)));