<?php
 declare(strict_types=1); namespace Jose\Component\Encryption\Serializer; use InvalidArgumentException; use Jose\Component\Encryption\JWE; use function sprintf; final class JWESerializerManager { private array $serializers = []; public function __construct(iterable $serializers) { foreach ($serializers as $serializer) { $this->add($serializer); } } public function names(): array { return array_keys($this->serializers); } public function serialize(string $name, JWE $jws, ?int $recipientIndex = null): string { if (! isset($this->serializers[$name])) { throw new InvalidArgumentException(sprintf('Unsupported serializer "%s".', $name)); } return $this->serializers[$name]->serialize($jws, $recipientIndex); } public function unserialize(string $input, ?string &$name = null): JWE { foreach ($this->serializers as $serializer) { try { $jws = $serializer->unserialize($input); $name = $serializer->name(); return $jws; } catch (InvalidArgumentException) { continue; } } throw new InvalidArgumentException('Unsupported input.'); } private function add(JWESerializer $serializer): void { $this->serializers[$serializer->name()] = $serializer; } } 