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: * Encoder delegating the decoding to a chain of encoders. Chris@0: * Chris@0: * @author Jordi Boggiano Chris@0: * @author Johannes M. Schmitt Chris@0: * @author Lukas Kahwe Smith Chris@0: */ Chris@0: class ChainEncoder implements EncoderInterface Chris@0: { Chris@0: protected $encoders = array(); Chris@0: protected $encoderByFormat = array(); Chris@0: Chris@0: public function __construct(array $encoders = array()) Chris@0: { Chris@0: $this->encoders = $encoders; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: final public function encode($data, $format, array $context = array()) Chris@0: { Chris@0: return $this->getEncoder($format)->encode($data, $format, $context); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function supportsEncoding($format) Chris@0: { Chris@0: try { Chris@0: $this->getEncoder($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: * Checks whether the normalization is needed for the given format. Chris@0: * Chris@0: * @param string $format Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: public function needsNormalization($format) Chris@0: { Chris@0: $encoder = $this->getEncoder($format); Chris@0: Chris@0: if (!$encoder instanceof NormalizationAwareInterface) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: if ($encoder instanceof self) { Chris@0: return $encoder->needsNormalization($format); Chris@0: } Chris@0: Chris@0: return false; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the encoder supporting the format. Chris@0: * Chris@0: * @param string $format Chris@0: * Chris@0: * @return EncoderInterface Chris@0: * Chris@0: * @throws RuntimeException if no encoder is found Chris@0: */ Chris@0: private function getEncoder($format) Chris@0: { Chris@0: if (isset($this->encoderByFormat[$format]) Chris@0: && isset($this->encoders[$this->encoderByFormat[$format]]) Chris@0: ) { Chris@0: return $this->encoders[$this->encoderByFormat[$format]]; Chris@0: } Chris@0: Chris@0: foreach ($this->encoders as $i => $encoder) { Chris@0: if ($encoder->supportsEncoding($format)) { Chris@0: $this->encoderByFormat[$format] = $i; Chris@0: Chris@0: return $encoder; Chris@0: } Chris@0: } Chris@0: Chris@0: throw new RuntimeException(sprintf('No encoder found for format "%s".', $format)); Chris@0: } Chris@0: }