FixedDataTransformer.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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\Tests\Fixtures;
  11. use Symfony\Component\Form\DataTransformerInterface;
  12. use Symfony\Component\Form\Exception\TransformationFailedException;
  13. class FixedDataTransformer implements DataTransformerInterface
  14. {
  15. private $mapping;
  16. public function __construct(array $mapping)
  17. {
  18. $this->mapping = $mapping;
  19. }
  20. public function transform($value)
  21. {
  22. if (!array_key_exists($value, $this->mapping)) {
  23. throw new TransformationFailedException(sprintf('No mapping for value "%s"', $value));
  24. }
  25. return $this->mapping[$value];
  26. }
  27. public function reverseTransform($value)
  28. {
  29. $result = array_search($value, $this->mapping, true);
  30. if (false === $result) {
  31. throw new TransformationFailedException(sprintf('No reverse mapping for value "%s"', $value));
  32. }
  33. return $result;
  34. }
  35. }