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

MemcachedCollector::collect()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 13
rs 9.4286
cc 3
eloc 7
nc 3
nop 0
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
}