| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Serializer\Encoder; |
| 13 |
|
| 14 |
use Symfony\Component\Serializer\Exception\RuntimeException; |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
class ChainDecoder implements ContextAwareDecoderInterface |
| 26 |
{ |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
private array $decoderByFormat = []; |
| 31 |
|
| 32 |
|
| 33 |
|
| 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 |
|
| 58 |
|
| 59 |
|
| 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 |
} |