vendor/symfony/form/Extension/Core/DataTransformer/ChoiceToValueTransformer.php line 32

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <[email protected]>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Form\Extension\Core\DataTransformer;
  11. use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
  12. use Symfony\Component\Form\DataTransformerInterface;
  13. use Symfony\Component\Form\Exception\TransformationFailedException;
  14. /**
  15. * @author Bernhard Schussek <[email protected]>
  16. */
  17. class ChoiceToValueTransformer implements DataTransformerInterface
  18. {
  19. private $choiceList;
  20. public function __construct(ChoiceListInterface $choiceList)
  21. {
  22. $this->choiceList = $choiceList;
  23. }
  24. public function transform($choice)
  25. {
  26. return (string) current($this->choiceList->getValuesForChoices([$choice]));
  27. }
  28. public function reverseTransform($value)
  29. {
  30. if (null !== $value && !\is_string($value)) {
  31. throw new TransformationFailedException('Expected a string or null.');
  32. }
  33. $choices = $this->choiceList->getChoicesForValues([(string) $value]);
  34. if (1 !== \count($choices)) {
  35. if (null === $value || '' === $value) {
  36. return null;
  37. }
  38. throw new TransformationFailedException(sprintf('The choice "%s" does not exist or is not unique.', $value));
  39. }
  40. return current($choices);
  41. }
  42. }