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 * @final since version 3.3.
25 class ChainDecoder implements DecoderInterface /*, ContextAwareDecoderInterface*/
27 protected $decoders = array();
28 protected $decoderByFormat = array();
30 public function __construct(array $decoders = array())
32 $this->decoders = $decoders;
38 final public function decode($data, $format, array $context = array())
40 return $this->getDecoder($format, $context)->decode($data, $format, $context);
46 public function supportsDecoding($format/*, array $context = array()*/)
48 $context = func_num_args() > 1 ? func_get_arg(1) : array();
51 $this->getDecoder($format, $context);
52 } catch (RuntimeException $e) {
60 * Gets the decoder supporting the format.
62 * @param string $format
63 * @param array $context
65 * @return DecoderInterface
67 * @throws RuntimeException if no decoder is found
69 private function getDecoder($format, array $context)
71 if (isset($this->decoderByFormat[$format])
72 && isset($this->decoders[$this->decoderByFormat[$format]])
74 return $this->decoders[$this->decoderByFormat[$format]];
77 foreach ($this->decoders as $i => $decoder) {
78 if ($decoder->supportsDecoding($format, $context)) {
79 $this->decoderByFormat[$format] = $i;
85 throw new RuntimeException(sprintf('No decoder found for format "%s".', $format));