|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Facile\OpenIDClient\Issuer\Metadata\Provider; |
|
6
|
|
|
|
|
7
|
|
|
use function is_array; |
|
8
|
|
|
use function json_decode; |
|
9
|
|
|
use function json_encode; |
|
10
|
|
|
use Psr\SimpleCache\CacheInterface; |
|
11
|
|
|
use function sha1; |
|
12
|
|
|
use function substr; |
|
13
|
|
|
|
|
14
|
|
|
final class CachedProviderDecorator implements RemoteProviderInterface |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var RemoteProviderInterface */ |
|
17
|
|
|
private $provider; |
|
18
|
|
|
|
|
19
|
|
|
/** @var CacheInterface */ |
|
20
|
|
|
private $cache; |
|
21
|
|
|
|
|
22
|
|
|
/** @var null|int */ |
|
23
|
|
|
private $cacheTtl; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var callable |
|
27
|
|
|
* @psalm-var callable(string): string |
|
28
|
|
|
*/ |
|
29
|
|
|
private $cacheIdGenerator; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @psalm-param null|callable(string): string $cacheIdGenerator |
|
33
|
|
|
*/ |
|
34
|
2 |
|
public function __construct( |
|
35
|
|
|
RemoteProviderInterface $provider, |
|
36
|
|
|
CacheInterface $cache, |
|
37
|
|
|
?int $cacheTtl = null, |
|
38
|
|
|
?callable $cacheIdGenerator = null |
|
39
|
|
|
) { |
|
40
|
2 |
|
$this->provider = $provider; |
|
41
|
2 |
|
$this->cache = $cache; |
|
42
|
2 |
|
$this->cacheTtl = $cacheTtl; |
|
43
|
2 |
|
$this->cacheIdGenerator = $cacheIdGenerator ?? static function (string $uri): string { |
|
44
|
2 |
|
return substr(sha1($uri), 0, 65); |
|
45
|
2 |
|
}; |
|
46
|
2 |
|
} |
|
47
|
|
|
|
|
48
|
2 |
|
public function fetch(string $uri): array |
|
49
|
|
|
{ |
|
50
|
2 |
|
$cacheId = ($this->cacheIdGenerator)($uri); |
|
51
|
|
|
|
|
52
|
|
|
/** @var string $cached */ |
|
53
|
2 |
|
$cached = $this->cache->get($cacheId) ?? ''; |
|
54
|
|
|
/** @var null|string|array<mixed> $data */ |
|
55
|
2 |
|
$data = json_decode($cached, true); |
|
56
|
|
|
|
|
57
|
2 |
|
if (is_array($data)) { |
|
58
|
1 |
|
return $data; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
1 |
|
$data = $this->provider->fetch($uri); |
|
62
|
|
|
|
|
63
|
1 |
|
$this->cache->set($cacheId, json_encode($data), $this->cacheTtl); |
|
64
|
|
|
|
|
65
|
1 |
|
return $data; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
public function isAllowedUri(string $uri): bool |
|
69
|
|
|
{ |
|
70
|
|
|
return $this->provider->isAllowedUri($uri); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|