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@14: * Chris@14: * @final since version 3.3. Chris@0: */ Chris@14: class ChainDecoder implements DecoderInterface /*, ContextAwareDecoderInterface*/ Chris@0: { Chris@17: protected $decoders = []; Chris@17: protected $decoderByFormat = []; Chris@0: Chris@17: public function __construct(array $decoders = []) Chris@0: { Chris@0: $this->decoders = $decoders; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@17: final public function decode($data, $format, array $context = []) Chris@0: { Chris@14: return $this->getDecoder($format, $context)->decode($data, $format, $context); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@17: public function supportsDecoding($format/*, array $context = []*/) Chris@0: { Chris@17: $context = \func_num_args() > 1 ? func_get_arg(1) : []; Chris@14: Chris@0: try { Chris@14: $this->getDecoder($format, $context); 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@14: * @param array $context Chris@0: * Chris@0: * @return DecoderInterface Chris@0: * Chris@14: * @throws RuntimeException if no decoder is found Chris@0: */ Chris@14: private function getDecoder($format, array $context) 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@14: if ($decoder->supportsDecoding($format, $context)) { 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: }