4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Serializer\Encoder;
14 use Symfony\Component\Serializer\Exception\RuntimeException;
17 * Decoder delegating the decoding to a chain of decoders.
19 * @author Jordi Boggiano <j.boggiano@seld.be>
20 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
21 * @author Lukas Kahwe Smith <smith@pooteeweet.org>
23 class ChainDecoder implements DecoderInterface
25 protected $decoders = array();
26 protected $decoderByFormat = array();
28 public function __construct(array $decoders = array())
30 $this->decoders = $decoders;
36 final public function decode($data, $format, array $context = array())
38 return $this->getDecoder($format)->decode($data, $format, $context);
44 public function supportsDecoding($format)
47 $this->getDecoder($format);
48 } catch (RuntimeException $e) {
56 * Gets the decoder supporting the format.
58 * @param string $format
60 * @return DecoderInterface
62 * @throws RuntimeException If no decoder is found.
64 private function getDecoder($format)
66 if (isset($this->decoderByFormat[$format])
67 && isset($this->decoders[$this->decoderByFormat[$format]])
69 return $this->decoders[$this->decoderByFormat[$format]];
72 foreach ($this->decoders as $i => $decoder) {
73 if ($decoder->supportsDecoding($format)) {
74 $this->decoderByFormat[$format] = $i;
80 throw new RuntimeException(sprintf('No decoder found for format "%s".', $format));