CachedProvider   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 95%

Importance

Changes 0
Metric Value
dl 0
loc 51
c 0
b 0
f 0
wmc 6
lcom 1
cbo 7
ccs 19
cts 20
cp 0.95
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setHashAlg() 0 4 1
A getCacheKey() 0 14 2
A getAuthorization() 0 4 1
A saveAuthorization() 0 8 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Facile\OAuth2\HttpClient\Authorization;
6
7
use Facile\OAuth2\HttpClient\Exception\RuntimeException;
8
use Facile\OAuth2\HttpClient\Request\OAuth2RequestInterface;
9
use Facile\OpenIDClient\Client\ClientInterface;
10
use Psr\SimpleCache\CacheInterface;
11
12
class CachedProvider implements AuthorizationProvider
13
{
14
    /** @var CacheInterface */
15
    private $cache;
16
17
    /** @var int */
18
    private $defaultTtl;
19
20
    /** @var string */
21
    private $hashAlg = 'sha1';
22
23 4
    public function __construct(CacheInterface $cache, int $defaultTtl = 1800)
24
    {
25 4
        $this->cache = $cache;
26 4
        $this->defaultTtl = $defaultTtl;
27 4
    }
28
29 1
    public function setHashAlg(string $hashAlg): void
30
    {
31 1
        $this->hashAlg = $hashAlg;
32 1
    }
33
34 4
    private function getCacheKey(ClientInterface $client, OAuth2RequestInterface $request): string
35
    {
36 4
        $encoded = json_encode([
37 4
            'issuer' => $client->getIssuer()->getMetadata()->getIssuer(),
38 4
            'client_id' => $client->getMetadata()->getClientId(),
39 4
            'grantParams' => $request->getGrantParams(),
40
        ]);
41
42 4
        if (! is_string($encoded)) {
43
            throw new RuntimeException('Unable to create cache key');
44
        }
45
46 4
        return hash($this->hashAlg, $encoded);
47
    }
48
49 1
    public function getAuthorization(ClientInterface $client, OAuth2RequestInterface $request): ?string
50
    {
51 1
        return $this->cache->get($this->getCacheKey($client, $request));
52
    }
53
54 3
    public function saveAuthorization(
55
        ClientInterface $client,
56
        OAuth2RequestInterface $request,
57
        string $authorization,
58
        ?int $ttl = null
59
    ): void {
60 3
        $this->cache->set($this->getCacheKey($client, $request), $authorization, $ttl ?? $this->defaultTtl);
61 3
    }
62
}
63