ebdfc70dfaf30ba412254eaa44b6328d40dc4071
[GitHub/WoltLab/WCF.git] /
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Signature\Serializer;
6
7 use InvalidArgumentException;
8 use Jose\Component\Signature\JWS;
9
10 class JWSSerializerManager
11 {
12 /**
13 * @var JWSSerializer[]
14 */
15 private array $serializers = [];
16
17 /**
18 * @param JWSSerializer[] $serializers
19 */
20 public function __construct(iterable $serializers)
21 {
22 foreach ($serializers as $serializer) {
23 $this->add($serializer);
24 }
25 }
26
27 /**
28 * @return string[]
29 */
30 public function list(): array
31 {
32 return array_keys($this->serializers);
33 }
34
35 /**
36 * Converts a JWS into a string.
37 */
38 public function serialize(string $name, JWS $jws, ?int $signatureIndex = null): string
39 {
40 if (! isset($this->serializers[$name])) {
41 throw new InvalidArgumentException(sprintf('Unsupported serializer "%s".', $name));
42 }
43
44 return $this->serializers[$name]->serialize($jws, $signatureIndex);
45 }
46
47 /**
48 * Loads data and return a JWS object.
49 *
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
52 */
53 public function unserialize(string $input, ?string &$name = null): JWS
54 {
55 foreach ($this->serializers as $serializer) {
56 try {
57 $jws = $serializer->unserialize($input);
58 $name = $serializer->name();
59
60 return $jws;
61 } catch (InvalidArgumentException) {
62 continue;
63 }
64 }
65
66 throw new InvalidArgumentException('Unsupported input.');
67 }
68
69 private function add(JWSSerializer $serializer): void
70 {
71 $this->serializers[$serializer->name()] = $serializer;
72 }
73 }