-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathDoctrineCache.php
More file actions
74 lines (55 loc) · 1.67 KB
/
Copy pathDoctrineCache.php
File metadata and controls
74 lines (55 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
namespace Noxlogic\RateLimitBundle\Service\Storage;
use Doctrine\Common\Cache\Cache;
use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
class DoctrineCache implements StorageInterface {
/**
* @var \Doctrine\Common\Cache\Cache
*/
protected $client;
public function __construct(Cache $client)
{
$this->client = $client;
}
public function getRateInfo($key)
{
$info = $this->client->fetch($key);
if ($info === false || !array_key_exists('limit', $info)) {
return false;
}
return $this->createRateInfo($info);
}
public function limitRate($key)
{
$info = $this->client->fetch($key);
if ($info === false || !array_key_exists('limit', $info)) {
return false;
}
$info['calls']++;
$expire = $info['reset'] - time();
$this->client->save($key, $info, $expire);
return $this->createRateInfo($info);
}
public function createRate($key, $limit, $period)
{
$info = array();
$info['limit'] = $limit;
$info['calls'] = 1;
$info['reset'] = time() + $period;
$this->client->save($key, $info, $period);
return $this->createRateInfo($info);
}
public function resetRate($key)
{
$this->client->delete($key);
return true;
}
private function createRateInfo(array $info): RateLimitInfo
{
$rateLimitInfo = new RateLimitInfo();
$rateLimitInfo->setLimit($info['limit']);
$rateLimitInfo->setCalls($info['calls']);
$rateLimitInfo->setResetTimestamp($info['reset']);
return $rateLimitInfo;
}
}