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

Redis   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 95.83%

Importance

Changes 4
Bugs 2 Features 0
Metric Value
wmc 6
c 4
b 2
f 0
lcom 1
cbo 1
dl 0
loc 51
ccs 23
cts 24
cp 0.9583
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A limitRate() 0 10 2
A createRate() 0 9 1
A getRateInfo() 0 11 1
A resetRate() 0 5 1
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