| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 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 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
class ChainEncoder implements ContextAwareEncoderInterface |
| 27 |
{ |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
private array $encoderByFormat = []; |
| 32 |
|
| 33 |
|
| 34 |
|
| 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 |
|
| 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 |
|
| 81 |
|
| 82 |
|
| 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 |
} |