CachedCredentials::getInner()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
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