Drupal investigation

ChainEncoder.php 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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\Serializer\Encoder;
  11. use Symfony\Component\Serializer\Exception\RuntimeException;
  12. /**
  13. * Encoder delegating the decoding to a chain of encoders.
  14. *
  15. * @author Jordi Boggiano <j.boggiano@seld.be>
  16. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  17. * @author Lukas Kahwe Smith <smith@pooteeweet.org>
  18. */
  19. class ChainEncoder implements EncoderInterface
  20. {
  21. protected $encoders = array();
  22. protected $encoderByFormat = array();
  23. public function __construct(array $encoders = array())
  24. {
  25. $this->encoders = $encoders;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. final public function encode($data, $format, array $context = array())
  31. {
  32. return $this->getEncoder($format)->encode($data, $format, $context);
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function supportsEncoding($format)
  38. {
  39. try {
  40. $this->getEncoder($format);
  41. } catch (RuntimeException $e) {
  42. return false;
  43. }
  44. return true;
  45. }
  46. /**
  47. * Checks whether the normalization is needed for the given format.
  48. *
  49. * @param string $format
  50. *
  51. * @return bool
  52. */
  53. public function needsNormalization($format)
  54. {
  55. $encoder = $this->getEncoder($format);
  56. if (!$encoder instanceof NormalizationAwareInterface) {
  57. return true;
  58. }
  59. if ($encoder instanceof self) {
  60. return $encoder->needsNormalization($format);
  61. }
  62. return false;
  63. }
  64. /**
  65. * Gets the encoder supporting the format.
  66. *
  67. * @param string $format
  68. *
  69. * @return EncoderInterface
  70. *
  71. * @throws RuntimeException if no encoder is found
  72. */
  73. private function getEncoder($format)
  74. {
  75. if (isset($this->encoderByFormat[$format])
  76. && isset($this->encoders[$this->encoderByFormat[$format]])
  77. ) {
  78. return $this->encoders[$this->encoderByFormat[$format]];
  79. }
  80. foreach ($this->encoders as $i => $encoder) {
  81. if ($encoder->supportsEncoding($format)) {
  82. $this->encoderByFormat[$format] = $i;
  83. return $encoder;
  84. }
  85. }
  86. throw new RuntimeException(sprintf('No encoder found for format "%s".', $format));
  87. }
  88. }