comparison vendor/symfony/serializer/Encoder/ChainDecoder.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 * Decoder delegating the decoding to a chain of decoders.
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 ChainDecoder implements DecoderInterface
24 {
25 protected $decoders = array();
26 protected $decoderByFormat = array();
27
28 public function __construct(array $decoders = array())
29 {
30 $this->decoders = $decoders;
31 }
32
33 /**
34 * {@inheritdoc}
35 */
36 final public function decode($data, $format, array $context = array())
37 {
38 return $this->getDecoder($format)->decode($data, $format, $context);
39 }
40
41 /**
42 * {@inheritdoc}
43 */
44 public function supportsDecoding($format)
45 {
46 try {
47 $this->getDecoder($format);
48 } catch (RuntimeException $e) {
49 return false;
50 }
51
52 return true;
53 }
54
55 /**
56 * Gets the decoder supporting the format.
57 *
58 * @param string $format
59 *
60 * @return DecoderInterface
61 *
62 * @throws RuntimeException If no decoder is found.
63 */
64 private function getDecoder($format)
65 {
66 if (isset($this->decoderByFormat[$format])
67 && isset($this->decoders[$this->decoderByFormat[$format]])
68 ) {
69 return $this->decoders[$this->decoderByFormat[$format]];
70 }
71
72 foreach ($this->decoders as $i => $decoder) {
73 if ($decoder->supportsDecoding($format)) {
74 $this->decoderByFormat[$format] = $i;
75
76 return $decoder;
77 }
78 }
79
80 throw new RuntimeException(sprintf('No decoder found for format "%s".', $format));
81 }
82 }