Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Encryption/Serializer/JWESerializerManager.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Encryption\Serializer;
6
7 use InvalidArgumentException;
8 use Jose\Component\Encryption\JWE;
9
10 class JWESerializerManager
11 {
12 /**
13 * @var JWESerializer[]
14 */
15 private array $serializers = [];
16
17 /**
18 * @param JWESerializer[] $serializers
19 */
20 public function __construct(iterable $serializers)
21 {
22 foreach ($serializers as $serializer) {
23 $this->add($serializer);
24 }
25 }
26
27 /**
28 * Return the serializer names supported by the manager.
29 *
30 * @return string[]
31 */
32 public function names(): array
33 {
34 return array_keys($this->serializers);
35 }
36
37 /**
38 * Converts a JWE into a string. Throws an exception if none of the serializer was able to convert the input.
39 */
40 public function serialize(string $name, JWE $jws, ?int $recipientIndex = null): string
41 {
42 if (! isset($this->serializers[$name])) {
43 throw new InvalidArgumentException(sprintf('Unsupported serializer "%s".', $name));
44 }
45
46 return $this->serializers[$name]->serialize($jws, $recipientIndex);
47 }
48
49 /**
50 * Loads data and return a JWE object. Throws an exception if none of the serializer was able to convert the input.
51 *
52 * @param string $input A string that represents a JWE
53 * @param string|null $name the name of the serializer if the input is unserialized
54 */
55 public function unserialize(string $input, ?string &$name = null): JWE
56 {
57 foreach ($this->serializers as $serializer) {
58 try {
59 $jws = $serializer->unserialize($input);
60 $name = $serializer->name();
61
62 return $jws;
63 } catch (InvalidArgumentException) {
64 continue;
65 }
66 }
67
68 throw new InvalidArgumentException('Unsupported input.');
69 }
70
71 /**
72 * Adds a serializer to the manager.
73 */
74 private function add(JWESerializer $serializer): void
75 {
76 $this->serializers[$serializer->name()] = $serializer;
77 }
78 }