Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Serializer\Encoder; Chris@0: Chris@0: use Symfony\Component\Serializer\Exception\RuntimeException; Chris@0: Chris@0: /** Chris@0: * Decoder delegating the decoding to a chain of decoders. Chris@0: * Chris@0: * @author Jordi Boggiano Chris@0: * @author Johannes M. Schmitt Chris@0: * @author Lukas Kahwe Smith Chris@0: */ Chris@0: class ChainDecoder implements DecoderInterface Chris@0: { Chris@0: protected $decoders = array(); Chris@0: protected $decoderByFormat = array(); Chris@0: Chris@0: public function __construct(array $decoders = array()) Chris@0: { Chris@0: $this->decoders = $decoders; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: final public function decode($data, $format, array $context = array()) Chris@0: { Chris@0: return $this->getDecoder($format)->decode($data, $format, $context); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function supportsDecoding($format) Chris@0: { Chris@0: try { Chris@0: $this->getDecoder($format); Chris@0: } catch (RuntimeException $e) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the decoder supporting the format. Chris@0: * Chris@0: * @param string $format Chris@0: * Chris@0: * @return DecoderInterface Chris@0: * Chris@0: * @throws RuntimeException If no decoder is found. Chris@0: */ Chris@0: private function getDecoder($format) Chris@0: { Chris@0: if (isset($this->decoderByFormat[$format]) Chris@0: && isset($this->decoders[$this->decoderByFormat[$format]]) Chris@0: ) { Chris@0: return $this->decoders[$this->decoderByFormat[$format]]; Chris@0: } Chris@0: Chris@0: foreach ($this->decoders as $i => $decoder) { Chris@0: if ($decoder->supportsDecoding($format)) { Chris@0: $this->decoderByFormat[$format] = $i; Chris@0: Chris@0: return $decoder; Chris@0: } Chris@0: } Chris@0: Chris@0: throw new RuntimeException(sprintf('No decoder found for format "%s".', $format)); Chris@0: } Chris@0: }