Drupal investigation

ChainDecoder.php 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. * Decoder delegating the decoding to a chain of decoders.
  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 ChainDecoder implements DecoderInterface
  20. {
  21. protected $decoders = array();
  22. protected $decoderByFormat = array();
  23. public function __construct(array $decoders = array())
  24. {
  25. $this->decoders = $decoders;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. final public function decode($data, $format, array $context = array())
  31. {
  32. return $this->getDecoder($format)->decode($data, $format, $context);
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function supportsDecoding($format)
  38. {
  39. try {
  40. $this->getDecoder($format);
  41. } catch (RuntimeException $e) {
  42. return false;
  43. }
  44. return true;
  45. }
  46. /**
  47. * Gets the decoder supporting the format.
  48. *
  49. * @param string $format
  50. *
  51. * @return DecoderInterface
  52. *
  53. * @throws RuntimeException If no decoder is found.
  54. */
  55. private function getDecoder($format)
  56. {
  57. if (isset($this->decoderByFormat[$format])
  58. && isset($this->decoders[$this->decoderByFormat[$format]])
  59. ) {
  60. return $this->decoders[$this->decoderByFormat[$format]];
  61. }
  62. foreach ($this->decoders as $i => $decoder) {
  63. if ($decoder->supportsDecoding($format)) {
  64. $this->decoderByFormat[$format] = $i;
  65. return $decoder;
  66. }
  67. }
  68. throw new RuntimeException(sprintf('No decoder found for format "%s".', $format));
  69. }
  70. }