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 * @final since version 3.3.
25 class ChainEncoder implements EncoderInterface /*, ContextAwareEncoderInterface*/
27 protected $encoders = array();
28 protected $encoderByFormat = array();
30 public function __construct(array $encoders = array())
32 $this->encoders = $encoders;
38 final public function encode($data, $format, array $context = array())
40 return $this->getEncoder($format, $context)->encode($data, $format, $context);
46 public function supportsEncoding($format/*, array $context = array()*/)
48 $context = \func_num_args() > 1 ? func_get_arg(1) : array();
51 $this->getEncoder($format, $context);
52 } catch (RuntimeException $e) {
60 * Checks whether the normalization is needed for the given format.
62 * @param string $format
63 * @param array $context
67 public function needsNormalization($format/*, array $context = array()*/)
69 $context = \func_num_args() > 1 ? func_get_arg(1) : array();
70 $encoder = $this->getEncoder($format, $context);
72 if (!$encoder instanceof NormalizationAwareInterface) {
76 if ($encoder instanceof self) {
77 return $encoder->needsNormalization($format, $context);
84 * Gets the encoder supporting the format.
86 * @param string $format
87 * @param array $context
89 * @return EncoderInterface
91 * @throws RuntimeException if no encoder is found
93 private function getEncoder($format, array $context)
95 if (isset($this->encoderByFormat[$format])
96 && isset($this->encoders[$this->encoderByFormat[$format]])
98 return $this->encoders[$this->encoderByFormat[$format]];
101 foreach ($this->encoders as $i => $encoder) {
102 if ($encoder->supportsEncoding($format, $context)) {
103 $this->encoderByFormat[$format] = $i;
109 throw new RuntimeException(sprintf('No encoder found for format "%s".', $format));