CachedCredentials   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 16
c 1
b 0
f 0
dl 0
loc 43
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A provide() 0 13 2
A getInner() 0 3 1
A __construct() 0 8 2
A getHash() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DigitalCz\DigiSign\Auth;
6
7
use DigitalCz\DigiSign\DigiSign;
8
use LogicException;
9
use Psr\SimpleCache\CacheInterface;
10
11
/**
12
 * Decorator to cache Credentials with PSR-16 CacheInterface
13
 */
14
final class CachedCredentials implements Credentials
15
{
16
    private const PREFIX = 'DGS_tok_';
17
18
    /** @var Credentials  */
19
    private $inner;
20
21
    /** @var CacheInterface  */
22
    private $cache;
23
24
    public function __construct(Credentials $inner, CacheInterface $cache)
25
    {
26
        if ($inner instanceof self) {
27
            throw new LogicException('Prevent double decoration');
28
        }
29
30
        $this->inner = $inner;
31
        $this->cache = $cache;
32
    }
33
34
    public function getHash(): string
35
    {
36
        return self::PREFIX . $this->inner->getHash();
37
    }
38
39
    public function provide(DigiSign $dgs): Token
40
    {
41
        $key = $this->getHash();
42
43
        if ($this->cache->has($key)) {
44
            return $this->cache->get($key);
45
        }
46
47
        $token = $this->inner->provide($dgs);
48
49
        $this->cache->set($key, $token, $token->getTtl());
50
51
        return $token;
52
    }
53
54
    public function getInner(): Credentials
55
    {
56
        return $this->inner;
57
    }
58
}
59