1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cmp\Cache\Infrastructure; |
4
|
|
|
|
5
|
|
|
use Cmp\Cache\Domain\Cache; |
6
|
|
|
use Cmp\Cache\Domain\ExceptionsException; |
7
|
|
|
use Cmp\Cache\Domain\Exceptions\NotFoundException; |
8
|
|
|
use Exception; |
9
|
|
|
use Redis; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class RedisCache |
13
|
|
|
* |
14
|
|
|
* A redis powered backend for caching |
15
|
|
|
* |
16
|
|
|
* @package Cmp\Cache\Infrastureture |
17
|
|
|
*/ |
18
|
|
|
class RedisCache implements Cache |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var Redis |
22
|
|
|
*/ |
23
|
|
|
private $client; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* RedisCache constructor. |
27
|
|
|
* |
28
|
|
|
* @param Redis $client |
29
|
|
|
*/ |
30
|
|
|
public function __construct(Redis $client) |
31
|
|
|
{ |
32
|
|
|
$this->client = $client; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* {@inheritdoc} |
37
|
|
|
*/ |
38
|
|
|
public function delete($key) |
39
|
|
|
{ |
40
|
|
|
try { |
41
|
|
|
$this->client->delete($key); |
42
|
|
|
} catch (Exception $exception) { |
43
|
|
|
throw new BackendException("Redis raised an exception deleting item $key", $exception); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* {@inheritdoc} |
49
|
|
|
*/ |
50
|
|
|
public function set($key, $value, $timeToLive = 0) |
51
|
|
|
{ |
52
|
|
|
try { |
53
|
|
|
if ($timeToLive > 0) { |
54
|
|
|
$this->client->setex($key, $timeToLive, $value); |
55
|
|
|
} else { |
56
|
|
|
$this->client->set($key, $value); |
57
|
|
|
} |
58
|
|
|
} catch (Exception $exception) { |
59
|
|
|
throw new BackendException("Redis raised an exception setting item $key", $exception); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* {@inheritdoc} |
65
|
|
|
*/ |
66
|
|
|
public function has($key) |
67
|
|
|
{ |
68
|
|
|
try { |
69
|
|
|
return $this->client->exists($key); |
70
|
|
|
} catch (Exception $exception) { |
71
|
|
|
throw new BackendException("Redis raised an exception checking for item $key", $exception); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* {@inheritdoc} |
77
|
|
|
*/ |
78
|
|
|
public function get($key) |
79
|
|
|
{ |
80
|
|
|
try { |
81
|
|
|
$value = $this->client->get($key); |
82
|
|
|
|
83
|
|
|
if (!$value && !$this->client->exists($key)) { |
84
|
|
|
throw new NotFoundException($key); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
return $value; |
88
|
|
|
} catch (NotFoundException $exception) { |
89
|
|
|
throw $exception; |
90
|
|
|
} catch (Exception $exception) { |
91
|
|
|
throw new BackendException("Redis raised an exception getting item $key", $exception); |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
/** |
96
|
|
|
* {@inheritdoc} |
97
|
|
|
*/ |
98
|
|
|
public function pull($key, $default = null) |
99
|
|
|
{ |
100
|
|
|
try { |
101
|
|
|
return $this->get($key); |
102
|
|
|
} catch (NotFoundException $exception) { |
103
|
|
|
return $default; |
104
|
|
|
} |
105
|
|
|
} |
106
|
|
|
} |
107
|
|
|
|