ValueTransformerChain.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace Symfony\Component\Form\ValueTransformer;
  3. /*
  4. * This file is part of the Symfony framework.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. /**
  12. * Passes a value through multiple value transformers
  13. *
  14. * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
  15. */
  16. class ValueTransformerChain implements ValueTransformerInterface
  17. {
  18. /**
  19. * The value transformers
  20. * @var array
  21. */
  22. protected $transformers;
  23. /**
  24. * Uses the given value transformers to transform values
  25. *
  26. * @param array $transformers
  27. */
  28. public function __construct(array $transformers)
  29. {
  30. $this->transformers = $transformers;
  31. }
  32. /**
  33. * Passes the value through the transform() method of all nested transformers
  34. *
  35. * The transformers receive the value in the same order as they were passed
  36. * to the constructor. Each transformer receives the result of the previous
  37. * transformer as input. The output of the last transformer is returned
  38. * by this method.
  39. *
  40. * @param mixed $value The original value
  41. * @return mixed The transformed value
  42. */
  43. public function transform($value)
  44. {
  45. foreach ($this->transformers as $transformer) {
  46. $value = $transformer->transform($value);
  47. }
  48. return $value;
  49. }
  50. /**
  51. * Passes the value through the reverseTransform() method of all nested
  52. * transformers
  53. *
  54. * The transformers receive the value in the reverse order as they were passed
  55. * to the constructor. Each transformer receives the result of the previous
  56. * transformer as input. The output of the last transformer is returned
  57. * by this method.
  58. *
  59. * @param mixed $value The transformed value
  60. * @return mixed The reverse-transformed value
  61. */
  62. public function reverseTransform($value)
  63. {
  64. for ($i = count($this->transformers) - 1; $i >= 0; --$i) {
  65. $value = $this->transformers[$i]->reverseTransform($value);
  66. }
  67. return $value;
  68. }
  69. /**
  70. * {@inheritDoc}
  71. */
  72. public function setLocale($locale)
  73. {
  74. foreach ($this->transformers as $transformer) {
  75. $transformer->setLocale($locale);
  76. }
  77. }
  78. }