1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Noxlogic\RateLimitBundle\Service\Storage; |
4
|
|
|
|
5
|
|
|
use Noxlogic\RateLimitBundle\Service\RateLimitInfo; |
6
|
|
|
use Predis\Client; |
7
|
|
|
|
8
|
|
|
class Redis implements StorageInterface |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var \Predis\Client |
12
|
|
|
*/ |
13
|
|
|
protected $client; |
14
|
|
|
|
15
|
5 |
|
public function __construct(Client $client) |
16
|
|
|
{ |
17
|
5 |
|
$this->client = $client; |
18
|
5 |
|
} |
19
|
|
|
|
20
|
3 |
|
public function getRateInfo($key) |
21
|
|
|
{ |
22
|
3 |
|
$info = $this->client->hgetall($key); |
23
|
|
|
|
24
|
3 |
|
$rateLimitInfo = new RateLimitInfo(); |
25
|
3 |
|
$rateLimitInfo->setLimit($info['limit']); |
26
|
3 |
|
$rateLimitInfo->setCalls($info['calls']); |
27
|
3 |
|
$rateLimitInfo->setResetTimestamp($info['reset']); |
28
|
|
|
|
29
|
3 |
|
return $rateLimitInfo; |
30
|
|
|
} |
31
|
|
|
|
32
|
2 |
|
public function limitRate($key) |
33
|
|
|
{ |
34
|
2 |
|
if (! $this->client->hexists($key, 'limit')) { |
35
|
1 |
|
return false; |
36
|
|
|
} |
37
|
|
|
|
38
|
1 |
|
$this->client->hincrby($key, 'calls', 1); |
39
|
|
|
|
40
|
1 |
|
return $this->getRateInfo($key); |
41
|
|
|
} |
42
|
|
|
|
43
|
1 |
|
public function createRate($key, $limit, $period) |
44
|
|
|
{ |
45
|
1 |
|
$this->client->hset($key, 'limit', $limit); |
46
|
1 |
|
$this->client->hset($key, 'calls', 1); |
47
|
1 |
|
$this->client->hset($key, 'reset', time() + $period); |
48
|
1 |
|
$this->client->expire($key, $period); |
49
|
|
|
|
50
|
1 |
|
return $this->getRateInfo($key); |
51
|
|
|
} |
52
|
|
|
|
53
|
1 |
|
public function resetRate($key) |
54
|
|
|
{ |
55
|
1 |
|
$this->client->del($key); |
56
|
|
|
return true; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|