comparison vendor/symfony/serializer/Encoder/ChainEncoder.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 1fec387a4317
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Serializer\Encoder;
13
14 use Symfony\Component\Serializer\Exception\RuntimeException;
15
16 /**
17 * Encoder delegating the decoding to a chain of encoders.
18 *
19 * @author Jordi Boggiano <j.boggiano@seld.be>
20 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
21 * @author Lukas Kahwe Smith <smith@pooteeweet.org>
22 */
23 class ChainEncoder implements EncoderInterface
24 {
25 protected $encoders = array();
26 protected $encoderByFormat = array();
27
28 public function __construct(array $encoders = array())
29 {
30 $this->encoders = $encoders;
31 }
32
33 /**
34 * {@inheritdoc}
35 */
36 final public function encode($data, $format, array $context = array())
37 {
38 return $this->getEncoder($format)->encode($data, $format, $context);
39 }
40
41 /**
42 * {@inheritdoc}
43 */
44 public function supportsEncoding($format)
45 {
46 try {
47 $this->getEncoder($format);
48 } catch (RuntimeException $e) {
49 return false;
50 }
51
52 return true;
53 }
54
55 /**
56 * Checks whether the normalization is needed for the given format.
57 *
58 * @param string $format
59 *
60 * @return bool
61 */
62 public function needsNormalization($format)
63 {
64 $encoder = $this->getEncoder($format);
65
66 if (!$encoder instanceof NormalizationAwareInterface) {
67 return true;
68 }
69
70 if ($encoder instanceof self) {
71 return $encoder->needsNormalization($format);
72 }
73
74 return false;
75 }
76
77 /**
78 * Gets the encoder supporting the format.
79 *
80 * @param string $format
81 *
82 * @return EncoderInterface
83 *
84 * @throws RuntimeException if no encoder is found
85 */
86 private function getEncoder($format)
87 {
88 if (isset($this->encoderByFormat[$format])
89 && isset($this->encoders[$this->encoderByFormat[$format]])
90 ) {
91 return $this->encoders[$this->encoderByFormat[$format]];
92 }
93
94 foreach ($this->encoders as $i => $encoder) {
95 if ($encoder->supportsEncoding($format)) {
96 $this->encoderByFormat[$format] = $i;
97
98 return $encoder;
99 }
100 }
101
102 throw new RuntimeException(sprintf('No encoder found for format "%s".', $format));
103 }
104 }