Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Signature/JWS.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Signature;
6
7 use InvalidArgumentException;
8 use Jose\Component\Core\JWT;
9 use function count;
10
11 /**
12 * @see \Jose\Tests\Component\Signature\JWSTest
13 */
14 class JWS implements JWT
15 {
16 /**
17 * @var Signature[]
18 */
19 private array $signatures = [];
20
21 public function __construct(
22 private readonly ?string $payload,
23 private readonly ?string $encodedPayload = null,
24 private readonly bool $isPayloadDetached = false
25 ) {
26 }
27
28 public function getPayload(): ?string
29 {
30 return $this->payload;
31 }
32
33 /**
34 * Returns true if the payload is detached.
35 */
36 public function isPayloadDetached(): bool
37 {
38 return $this->isPayloadDetached;
39 }
40
41 /**
42 * Returns the Base64Url encoded payload. If the payload is detached, this method returns null.
43 */
44 public function getEncodedPayload(): ?string
45 {
46 if ($this->isPayloadDetached() === true) {
47 return null;
48 }
49
50 return $this->encodedPayload;
51 }
52
53 /**
54 * Returns the signatures associated with the JWS.
55 *
56 * @return Signature[]
57 */
58 public function getSignatures(): array
59 {
60 return $this->signatures;
61 }
62
63 /**
64 * Returns the signature at the given index.
65 */
66 public function getSignature(int $id): Signature
67 {
68 if (isset($this->signatures[$id])) {
69 return $this->signatures[$id];
70 }
71
72 throw new InvalidArgumentException('The signature does not exist.');
73 }
74
75 /**
76 * This method adds a signature to the JWS object. Its returns a new JWS object.
77 *
78 * @internal
79 *
80 * @param array{alg?: string, string?: mixed} $protectedHeader
81 * @param array{alg?: string, string?: mixed} $header
82 */
83 public function addSignature(
84 string $signature,
85 array $protectedHeader,
86 ?string $encodedProtectedHeader,
87 array $header = []
88 ): self {
89 $jws = clone $this;
90 $jws->signatures[] = new Signature($signature, $protectedHeader, $encodedProtectedHeader, $header);
91
92 return $jws;
93 }
94
95 /**
96 * Returns the number of signature associated with the JWS.
97 */
98 public function countSignatures(): int
99 {
100 return count($this->signatures);
101 }
102
103 /**
104 * This method splits the JWS into a list of JWSs. It is only useful when the JWS contains more than one signature
105 * (JSON General Serialization).
106 *
107 * @return JWS[]
108 */
109 public function split(): array
110 {
111 $result = [];
112 foreach ($this->signatures as $signature) {
113 $jws = new self($this->payload, $this->encodedPayload, $this->isPayloadDetached);
114 $jws = $jws->addSignature(
115 $signature->getSignature(),
116 $signature->getProtectedHeader(),
117 $signature->getEncodedProtectedHeader(),
118 $signature->getHeader()
119 );
120
121 $result[] = $jws;
122 }
123
124 return $result;
125 }
126 }