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