1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Noxlogic\RateLimitBundle\Service\Storage; |
4
|
|
|
|
5
|
|
|
use Noxlogic\RateLimitBundle\Service\RateLimitInfo; |
6
|
|
|
use Predis\Client; |
7
|
|
|
|
8
|
|
View Code Duplication |
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
|
3 |
|
if (!isset($info['limit']) || !isset($info['calls']) || !isset($info['reset'])) { |
24
|
1 |
|
return false; |
|
|
|
|
25
|
|
|
} |
26
|
|
|
|
27
|
2 |
|
$rateLimitInfo = new RateLimitInfo(); |
28
|
2 |
|
$rateLimitInfo->setLimit($info['limit']); |
29
|
2 |
|
$rateLimitInfo->setCalls($info['calls']); |
30
|
2 |
|
$rateLimitInfo->setResetTimestamp($info['reset']); |
31
|
|
|
|
32
|
2 |
|
return $rateLimitInfo; |
33
|
|
|
} |
34
|
|
|
|
35
|
2 |
|
public function limitRate($key) |
36
|
|
|
{ |
37
|
2 |
|
$info = $this->getRateInfo($key); |
38
|
2 |
|
if (!$info) { |
39
|
1 |
|
return false; |
|
|
|
|
40
|
|
|
} |
41
|
|
|
|
42
|
1 |
|
$this->client->hincrby($key, 'calls', 1); |
43
|
|
|
|
44
|
1 |
|
return $info; |
45
|
|
|
} |
46
|
|
|
|
47
|
1 |
|
public function createRate($key, $limit, $period) |
48
|
|
|
{ |
49
|
1 |
|
$reset = time() + $period; |
50
|
|
|
|
51
|
1 |
|
$this->client->hset($key, 'limit', $limit); |
52
|
1 |
|
$this->client->hset($key, 'calls', 1); |
53
|
1 |
|
$this->client->hset($key, 'reset', $reset); |
54
|
1 |
|
$this->client->expire($key, $period); |
55
|
|
|
|
56
|
1 |
|
$rateLimitInfo = new RateLimitInfo(); |
57
|
1 |
|
$rateLimitInfo->setLimit($limit); |
58
|
1 |
|
$rateLimitInfo->setCalls(1); |
59
|
1 |
|
$rateLimitInfo->setResetTimestamp($reset); |
60
|
|
|
|
61
|
1 |
|
return $rateLimitInfo; |
62
|
|
|
} |
63
|
|
|
|
64
|
1 |
|
public function resetRate($key) |
65
|
|
|
{ |
66
|
1 |
|
$this->client->del($key); |
67
|
|
|
|
68
|
1 |
|
return true; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
} |
72
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.