Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Encoder/ChainEncoder.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\Debug\TraceableEncoder;
15 use Symfony\Component\Serializer\Exception\RuntimeException;
16
17 /**
18 * Encoder delegating the decoding to a chain of encoders.
19 *
20 * @author Jordi Boggiano <[email protected]>
21 * @author Johannes M. Schmitt <[email protected]>
22 * @author Lukas Kahwe Smith <[email protected]>
23 *
24 * @final
25 */
26 class ChainEncoder implements ContextAwareEncoderInterface
27 {
28 /**
29 * @var array<string, array-key>
30 */
31 private array $encoderByFormat = [];
32
33 /**
34 * @param array<EncoderInterface> $encoders
35 */
36 public function __construct(
37 private readonly array $encoders = [],
38 ) {
39 }
40
41 final public function encode(mixed $data, string $format, array $context = []): string
42 {
43 return $this->getEncoder($format, $context)->encode($data, $format, $context);
44 }
45
46 public function supportsEncoding(string $format, array $context = []): bool
47 {
48 try {
49 $this->getEncoder($format, $context);
50 } catch (RuntimeException) {
51 return false;
52 }
53
54 return true;
55 }
56
57 /**
58 * Checks whether the normalization is needed for the given format.
59 */
60 public function needsNormalization(string $format, array $context = []): bool
61 {
62 $encoder = $this->getEncoder($format, $context);
63
64 if ($encoder instanceof TraceableEncoder) {
65 return $encoder->needsNormalization();
66 }
67
68 if (!$encoder instanceof NormalizationAwareInterface) {
69 return true;
70 }
71
72 if ($encoder instanceof self) {
73 return $encoder->needsNormalization($format, $context);
74 }
75
76 return false;
77 }
78
79 /**
80 * Gets the encoder supporting the format.
81 *
82 * @throws RuntimeException if no encoder is found
83 */
84 private function getEncoder(string $format, array $context): EncoderInterface
85 {
86 if (isset($this->encoderByFormat[$format])
87 && isset($this->encoders[$this->encoderByFormat[$format]])
88 ) {
89 return $this->encoders[$this->encoderByFormat[$format]];
90 }
91
92 $cache = true;
93 foreach ($this->encoders as $i => $encoder) {
94 $cache = $cache && !$encoder instanceof ContextAwareEncoderInterface;
95 if ($encoder->supportsEncoding($format, $context)) {
96 if ($cache) {
97 $this->encoderByFormat[$format] = $i;
98 }
99
100 return $encoder;
101 }
102 }
103
104 throw new RuntimeException(\sprintf('No encoder found for format "%s".', $format));
105 }
106 }