Completed
Pull Request — master (#31)
by Joshua
09:37 queued 07:24
created

Redis::resetRate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.037

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 5
ccs 2
cts 3
cp 0.6667
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1.037
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