Completed
Push — master ( 066d89...19607d )
by De
01:54
created

MemcachedCollector   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 6
c 2
b 0
f 0
lcom 1
cbo 1
dl 0
loc 40
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setMemcached() 0 5 1
A isRateLimitExceed() 0 12 2
A collect() 0 13 3
1
<?php
2
3
namespace Sokil\FraudDetector\Collector;
4
5
/**
6
 * @property \Memcached $storage Instance of \Memcached storage
7
 */
8
class MemcachedCollector extends AbstractCollector
9
{
10
    /**
11
     * @var \Memcached
12
     */
13
    private $memcached;
14
15
    public function setMemcached(\Memcached $memcached)
16
    {
17
        $this->memcached = $memcached;
18
        return $this;
19
    }
20
21
    public function isRateLimitExceed()
22
    {
23
        $requestNum = $this->memcached->get($this->key);
24
25
        // is key not exists
26
        if(\Memcached::RES_NOTFOUND === $this->memcached->getResultCode()) {
27
            return false;
28
        }
29
30
        // is requests limit reached
31
        return $requestNum >= $this->requestNum;
32
    }
33
34
    public function collect()
35
    {
36
        $newValue = $this->memcached->increment($this->key);
37
        if(false !== $newValue) {
38
            return $this;
39
        }
40
41
        if(\Memcached::RES_NOTFOUND !== $this->memcached->getResultCode()) {
42
            throw new \Exception('Error collecting value');
43
        }
44
45
        $this->memcached->set($this->key, 1, time() + $this->timeInterval);
46
    }
47
}