RedisStorage::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Damax\Bundle\ApiAuthBundle\Key\Storage;
6
7
use Damax\Bundle\ApiAuthBundle\Key\Key;
8
use Predis\ClientInterface;
9
10
final class RedisStorage implements Storage
11
{
12
    private $client;
13
    private $prefix;
14
15
    public function __construct(ClientInterface $client, string $prefix = '')
16
    {
17
        $this->client = $client;
18
        $this->prefix = $prefix;
19
    }
20
21
    public function has(string $key): bool
22
    {
23
        $storageKey = $this->storageKey($key);
24
25
        return (bool) $this->client->exists($storageKey);
26
    }
27
28
    public function get(string $key): Key
29
    {
30
        $storageKey = $this->storageKey($key);
31
32
        if (null === $identity = $this->client->get($storageKey)) {
33
            throw new KeyNotFound();
34
        }
35
36
        return new Key($key, $identity, $this->client->ttl($storageKey));
37
    }
38
39
    public function add(Key $key): void
40
    {
41
        $storageKey = $this->storageKey((string) $key);
42
43
        $this->client->setex($storageKey, $key->ttl(), $key->identity());
44
    }
45
46
    public function remove(string $key): void
47
    {
48
        $storageKey = $this->storageKey($key);
49
50
        $this->client->del([$storageKey]);
51
    }
52
53
    private function storageKey(string $key): string
54
    {
55
        return $this->prefix . $key;
56
    }
57
}
58