Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 /*
|
Chris@0
|
4 * This file is part of the Symfony package.
|
Chris@0
|
5 *
|
Chris@0
|
6 * (c) Fabien Potencier <fabien@symfony.com>
|
Chris@0
|
7 *
|
Chris@0
|
8 * For the full copyright and license information, please view the LICENSE
|
Chris@0
|
9 * file that was distributed with this source code.
|
Chris@0
|
10 */
|
Chris@0
|
11
|
Chris@0
|
12 namespace Symfony\Component\Serializer\Encoder;
|
Chris@0
|
13
|
Chris@0
|
14 use Symfony\Component\Serializer\Exception\RuntimeException;
|
Chris@0
|
15
|
Chris@0
|
16 /**
|
Chris@0
|
17 * Decoder delegating the decoding to a chain of decoders.
|
Chris@0
|
18 *
|
Chris@0
|
19 * @author Jordi Boggiano <j.boggiano@seld.be>
|
Chris@0
|
20 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
|
Chris@0
|
21 * @author Lukas Kahwe Smith <smith@pooteeweet.org>
|
Chris@0
|
22 */
|
Chris@0
|
23 class ChainDecoder implements DecoderInterface
|
Chris@0
|
24 {
|
Chris@0
|
25 protected $decoders = array();
|
Chris@0
|
26 protected $decoderByFormat = array();
|
Chris@0
|
27
|
Chris@0
|
28 public function __construct(array $decoders = array())
|
Chris@0
|
29 {
|
Chris@0
|
30 $this->decoders = $decoders;
|
Chris@0
|
31 }
|
Chris@0
|
32
|
Chris@0
|
33 /**
|
Chris@0
|
34 * {@inheritdoc}
|
Chris@0
|
35 */
|
Chris@0
|
36 final public function decode($data, $format, array $context = array())
|
Chris@0
|
37 {
|
Chris@0
|
38 return $this->getDecoder($format)->decode($data, $format, $context);
|
Chris@0
|
39 }
|
Chris@0
|
40
|
Chris@0
|
41 /**
|
Chris@0
|
42 * {@inheritdoc}
|
Chris@0
|
43 */
|
Chris@0
|
44 public function supportsDecoding($format)
|
Chris@0
|
45 {
|
Chris@0
|
46 try {
|
Chris@0
|
47 $this->getDecoder($format);
|
Chris@0
|
48 } catch (RuntimeException $e) {
|
Chris@0
|
49 return false;
|
Chris@0
|
50 }
|
Chris@0
|
51
|
Chris@0
|
52 return true;
|
Chris@0
|
53 }
|
Chris@0
|
54
|
Chris@0
|
55 /**
|
Chris@0
|
56 * Gets the decoder supporting the format.
|
Chris@0
|
57 *
|
Chris@0
|
58 * @param string $format
|
Chris@0
|
59 *
|
Chris@0
|
60 * @return DecoderInterface
|
Chris@0
|
61 *
|
Chris@0
|
62 * @throws RuntimeException If no decoder is found.
|
Chris@0
|
63 */
|
Chris@0
|
64 private function getDecoder($format)
|
Chris@0
|
65 {
|
Chris@0
|
66 if (isset($this->decoderByFormat[$format])
|
Chris@0
|
67 && isset($this->decoders[$this->decoderByFormat[$format]])
|
Chris@0
|
68 ) {
|
Chris@0
|
69 return $this->decoders[$this->decoderByFormat[$format]];
|
Chris@0
|
70 }
|
Chris@0
|
71
|
Chris@0
|
72 foreach ($this->decoders as $i => $decoder) {
|
Chris@0
|
73 if ($decoder->supportsDecoding($format)) {
|
Chris@0
|
74 $this->decoderByFormat[$format] = $i;
|
Chris@0
|
75
|
Chris@0
|
76 return $decoder;
|
Chris@0
|
77 }
|
Chris@0
|
78 }
|
Chris@0
|
79
|
Chris@0
|
80 throw new RuntimeException(sprintf('No decoder found for format "%s".', $format));
|
Chris@0
|
81 }
|
Chris@0
|
82 }
|