1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Audiens\AdForm\Cache; |
4
|
|
|
|
5
|
|
|
use Audiens\AdForm\Exception\RedisException; |
6
|
|
|
use Predis\Client; |
7
|
|
|
use Predis\Response\ServerException; |
8
|
|
|
|
9
|
|
|
class RedisCache extends BaseCache implements CacheInterface |
10
|
|
|
{ |
11
|
|
|
/** @var Client */ |
12
|
|
|
private $client; |
13
|
|
|
|
14
|
|
|
/** @var int */ |
15
|
|
|
private $ttl; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* TODO breaking change: move Predis\Client as dependency |
19
|
|
|
* |
20
|
|
|
* @param array $config |
21
|
|
|
* @param int $ttl |
22
|
|
|
* @param string $prefix |
23
|
|
|
* |
24
|
|
|
* @throws RedisException |
25
|
|
|
*/ |
26
|
|
|
public function __construct(array $config, int $ttl = 3600, $prefix = 'adform_') |
27
|
|
|
{ |
28
|
|
|
parent::__construct($prefix); |
29
|
|
|
|
30
|
|
|
$this->ttl = $ttl; |
31
|
|
|
|
32
|
|
|
try { |
33
|
|
|
$this->client = new Client($config); |
34
|
|
|
} catch (ServerException $e) { |
35
|
|
|
throw RedisException::connect($e->getMessage()); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function put(string $providerPrefix, string $uri, array $query, string $data): bool |
40
|
|
|
{ |
41
|
|
|
$hash = $this->getHash($providerPrefix, $uri, $query); |
42
|
|
|
|
43
|
|
|
return (bool) $this->client->set($hash, $data, 'ex', $this->ttl); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function get(string $providerPrefix, string $uri, array $query) |
47
|
|
|
{ |
48
|
|
|
$hash = $this->getHash($providerPrefix, $uri, $query); |
49
|
|
|
|
50
|
|
|
$data = $this->client->get($hash); |
51
|
|
|
|
52
|
|
|
if (!empty($data)) { |
53
|
|
|
return $data; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return false; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function delete(string $providerPrefix, string $uri, array $query): bool |
60
|
|
|
{ |
61
|
|
|
$hash = $this->getHash($providerPrefix, $uri, $query); |
62
|
|
|
|
63
|
|
|
return (bool) $this->client->del([$hash]); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
public function invalidate(string $providerPrefix): bool |
67
|
|
|
{ |
68
|
|
|
$keys = $this->client->keys($this->prefix.strtolower($providerPrefix).'_*'); |
69
|
|
|
|
70
|
|
|
$this->client->del($keys); |
71
|
|
|
|
72
|
|
|
return true; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|