Debian Codegraph @

lib/3rdParty/composer/facile-it/php-jose-verifier/src/JWK/CachedJwksProvider.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\SimpleCache\CacheInterface;
10
11 use function is_string;
12 use function json_decode;
13 use function json_encode;
14
15 /**
16 * Wrapper to provide cache feature for a {@see JwksProviderInterface}.
17 *
18 * @psalm-api
19 */
20 final class CachedJwksProvider extends AbstractJwksProvider
21 {
22 private JwksProviderInterface $provider;
23
24 private CacheInterface $cache;
25
26 private string $cacheKey;
27
28 private ?int $ttl;
29
30 public function __construct(JwksProviderInterface $provider, CacheInterface $cache, string $cacheKey, ?int $ttl)
31 {
32 $this->provider = $provider;
33 $this->cache = $cache;
34 $this->cacheKey = $cacheKey;
35 $this->ttl = $ttl;
36 }
37
38 /**
39 * @throws RuntimeException Whenever a runtime error occurred
40 */
41 public function getJwks(): array
42 {
43 try {
44 /** @var null|string $cached */
45 $cached = $this->cache->get($this->cacheKey);
46 } catch (\Psr\SimpleCache\InvalidArgumentException $e) {
47 throw new RuntimeException('An error occurred fetching cached JWKSet', 0, $e);
48 }
49
50 if (is_string($cached)) {
51 try {
52 /** @var mixed $jwks */
53 $jwks = json_decode($cached, true, 512, JSON_THROW_ON_ERROR);
54 } catch (JsonException $e) {
55 throw new RuntimeException('Unable to decode cached JWKSet', 0, $e);
56 }
57
58 if ($this->isJWKSet($jwks)) {
59 return $jwks;
60 }
61 }
62
63 $jwks = $this->provider->getJwks();
64
65 try {
66 $this->cache->set($this->cacheKey, json_encode($jwks, JSON_THROW_ON_ERROR), $this->ttl);
67 } catch (JsonException $e) {
68 throw new RuntimeException('Unable to encode JWKSet before cache', 0, $e);
69 } catch (\Psr\SimpleCache\InvalidArgumentException $e) {
70 throw new RuntimeException('An error occurred saving JWKSet in cache', 0, $e);
71 }
72
73 return $jwks;
74 }
75
76 /**
77 * @throws RuntimeException
78 */
79 public function reload(): static
80 {
81 try {
82 $this->cache->delete($this->cacheKey);
83 } catch (\Psr\SimpleCache\InvalidArgumentException $e) {
84 throw new RuntimeException('An error occurred deleting JWKSet from cache', 0, $e);
85 }
86
87 return $this;
88 }
89 }