3 declare(strict_types=1);
5 namespace Jose\Component\Signature\Serializer;
7 use InvalidArgumentException;
8 use Jose\Component\Signature\JWS;
10 class JWSSerializerManager
13 * @var JWSSerializer[]
15 private array $serializers = [];
18 * @param JWSSerializer[] $serializers
20 public function __construct(iterable $serializers)
22 foreach ($serializers as $serializer) {
23 $this->add($serializer);
30 public function list(): array
32 return array_keys($this->serializers);
36 * Converts a JWS into a string.
38 public function serialize(string $name, JWS $jws, ?int $signatureIndex = null): string
40 if (! isset($this->serializers[$name])) {
41 throw new InvalidArgumentException(sprintf('Unsupported serializer "%s".', $name));
44 return $this->serializers[$name]->serialize($jws, $signatureIndex);
48 * Loads data and return a JWS object.
50 * @param string $input A string that represents a JWS
51 * @param string|null $name the name of the serializer if the input is unserialized
53 public function unserialize(string $input, ?string &$name = null): JWS
55 foreach ($this->serializers as $serializer) {
57 $jws = $serializer->unserialize($input);
58 $name = $serializer->name();
61 } catch (InvalidArgumentException) {
66 throw new InvalidArgumentException('Unsupported input.');
69 private function add(JWSSerializer $serializer): void
71 $this->serializers[$serializer->name()] = $serializer;