Debian Codegraph @

lib/3rdParty/composer/facile-it/php-jose-verifier/src/JWK/RemoteJwksProvider.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Facile\JoseVerifier\JWK;
6
7 use Facile\JoseVerifier\Exception\RuntimeException;
8 use JsonException;
9 use Psr\Http\Client\ClientExceptionInterface;
10 use Psr\Http\Client\ClientInterface;
11 use Psr\Http\Message\RequestFactoryInterface;
12 use Psr\Http\Message\RequestInterface;
13
14 use function json_decode;
15
16 /**
17 * Provide a {@see JwksProviderInterface} to fetch JWKSet from a remote location.
18 *
19 * @psalm-api
20 */
21 final class RemoteJwksProvider extends AbstractJwksProvider
22 {
23 private ClientInterface $client;
24
25 private RequestFactoryInterface $requestFactory;
26
27 private string $uri;
28
29 /** @var array<string, string|string[]> */
30 private array $headers;
31
32 /**
33 * @param array<string, string|string[]> $headers
34 */
35 public function __construct(
36 ClientInterface $client,
37 RequestFactoryInterface $requestFactory,
38 string $uri,
39 array $headers = []
40 ) {
41 $this->client = $client;
42 $this->requestFactory = $requestFactory;
43 $this->uri = $uri;
44 $this->headers = $headers;
45 }
46
47 /**
48 * @param array<string, string|string[]> $headers
49 */
50 public function withHeaders(array $headers): static
51 {
52 $new = clone $this;
53 $new->headers = $headers;
54
55 return $new;
56 }
57
58 /**
59 * @throws RuntimeException Whenever a runtime error occurred
60 */
61 public function getJwks(): array
62 {
63 $request = $this->requestFactory->createRequest('GET', $this->uri);
64
65 foreach ($this->headers as $k => $v) {
66 /** @var RequestInterface $request */
67 $request = $request->withHeader($k, $v);
68 }
69
70 try {
71 $response = $this->client->sendRequest($request);
72 } catch (ClientExceptionInterface $e) {
73 throw new RuntimeException('An error occurred fetching JWKSet', 0, $e);
74 }
75
76 if ($response->getStatusCode() >= 400) {
77 throw new RuntimeException('Unable to get the key set', $response->getStatusCode());
78 }
79
80 try {
81 /** @var mixed $data */
82 $data = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
83 } catch (JsonException $e) {
84 throw new RuntimeException('Unable to decode response payload', 0, $e);
85 }
86
87 if ($this->isJWKSet($data)) {
88 return $data;
89 }
90
91 throw new RuntimeException('Invalid key set content');
92 }
93
94 public function reload(): static
95 {
96 return $this;
97 }
98 }