CallbackTransformer.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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;
  11. use Symfony\Component\Form\Exception\TransformationFailedException;
  12. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  13. class CallbackTransformer implements DataTransformerInterface
  14. {
  15. private $transform;
  16. private $reverseTransform;
  17. /**
  18. * @param callable $transform The forward transform callback
  19. * @param callable $reverseTransform The reverse transform callback
  20. *
  21. * @throws \InvalidArgumentException when the given callbacks is invalid
  22. */
  23. public function __construct($transform, $reverseTransform)
  24. {
  25. if (!\is_callable($transform)) {
  26. throw new \InvalidArgumentException('Argument 1 should be a callable');
  27. }
  28. if (!\is_callable($reverseTransform)) {
  29. throw new \InvalidArgumentException('Argument 2 should be a callable');
  30. }
  31. $this->transform = $transform;
  32. $this->reverseTransform = $reverseTransform;
  33. }
  34. /**
  35. * Transforms a value from the original representation to a transformed representation.
  36. *
  37. * @param mixed $data The value in the original representation
  38. *
  39. * @return mixed The value in the transformed representation
  40. *
  41. * @throws UnexpectedTypeException when the argument is not of the expected type
  42. * @throws TransformationFailedException when the transformation fails
  43. */
  44. public function transform($data)
  45. {
  46. return \call_user_func($this->transform, $data);
  47. }
  48. /**
  49. * Transforms a value from the transformed representation to its original
  50. * representation.
  51. *
  52. * @param mixed $data The value in the transformed representation
  53. *
  54. * @return mixed The value in the original representation
  55. *
  56. * @throws UnexpectedTypeException when the argument is not of the expected type
  57. * @throws TransformationFailedException when the transformation fails
  58. */
  59. public function reverseTransform($data)
  60. {
  61. return \call_user_func($this->reverseTransform, $data);
  62. }
  63. }