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 * Encoder delegating the decoding to a chain of encoders.
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 ChainEncoder implements EncoderInterface
25 protected $encoders = array();
26 protected $encoderByFormat = array();
28 public function __construct(array $encoders = array())
30 $this->encoders = $encoders;
36 final public function encode($data, $format, array $context = array())
38 return $this->getEncoder($format)->encode($data, $format, $context);
44 public function supportsEncoding($format)
47 $this->getEncoder($format);
48 } catch (RuntimeException $e) {
56 * Checks whether the normalization is needed for the given format.
58 * @param string $format
62 public function needsNormalization($format)
64 $encoder = $this->getEncoder($format);
66 if (!$encoder instanceof NormalizationAwareInterface) {
70 if ($encoder instanceof self) {
71 return $encoder->needsNormalization($format);
78 * Gets the encoder supporting the format.
80 * @param string $format
82 * @return EncoderInterface
84 * @throws RuntimeException if no encoder is found
86 private function getEncoder($format)
88 if (isset($this->encoderByFormat[$format])
89 && isset($this->encoders[$this->encoderByFormat[$format]])
91 return $this->encoders[$this->encoderByFormat[$format]];
94 foreach ($this->encoders as $i => $encoder) {
95 if ($encoder->supportsEncoding($format)) {
96 $this->encoderByFormat[$format] = $i;
102 throw new RuntimeException(sprintf('No encoder found for format "%s".', $format));