Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Encoder/ChainDecoder.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
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 <[email protected]>
20 * @author Johannes M. Schmitt <[email protected]>
21 * @author Lukas Kahwe Smith <[email protected]>
22 *
23 * @final
24 */
25 class ChainDecoder implements ContextAwareDecoderInterface
26 {
27 /**
28 * @var array<string, array-key>
29 */
30 private array $decoderByFormat = [];
31
32 /**
33 * @param array<DecoderInterface> $decoders
34 */
35 public function __construct(
36 private readonly array $decoders = [],
37 ) {
38 }
39
40 final public function decode(string $data, string $format, array $context = []): mixed
41 {
42 return $this->getDecoder($format, $context)->decode($data, $format, $context);
43 }
44
45 public function supportsDecoding(string $format, array $context = []): bool
46 {
47 try {
48 $this->getDecoder($format, $context);
49 } catch (RuntimeException) {
50 return false;
51 }
52
53 return true;
54 }
55
56 /**
57 * Gets the decoder supporting the format.
58 *
59 * @throws RuntimeException if no decoder is found
60 */
61 private function getDecoder(string $format, array $context): DecoderInterface
62 {
63 if (isset($this->decoderByFormat[$format])
64 && isset($this->decoders[$this->decoderByFormat[$format]])
65 ) {
66 return $this->decoders[$this->decoderByFormat[$format]];
67 }
68
69 $cache = true;
70 foreach ($this->decoders as $i => $decoder) {
71 $cache = $cache && !$decoder instanceof ContextAwareDecoderInterface;
72 if ($decoder->supportsDecoding($format, $context)) {
73 if ($cache) {
74 $this->decoderByFormat[$format] = $i;
75 }
76
77 return $decoder;
78 }
79 }
80
81 throw new RuntimeException(\sprintf('No decoder found for format "%s".', $format));
82 }
83 }