ChainDecoder.php 2.0 KB

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