Completed
Push — master ( c077e9...4fc007 )
by John
02:06
created

CachePoolThrottle::logRequest()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 2
1
<?php
2
namespace LunixREST\Throttle;
3
4
use LunixREST\APIRequest\APIRequest;
5
use Psr\Cache\CacheItemPoolInterface;
6
7
/**
8
 * A Throttle implementation that relies on an underlying CacheItemPool, and allows a certain number requests in a certain number of seconds.
9
 * Class CachePoolThrottle
10
 * @package LunixREST\Throttle
11
 */
12
abstract class CachePoolThrottle implements Throttle
13
{
14
    /**
15
     * @var CacheItemPoolInterface
16
     */
17
    private $cacheItemPool;
18
    /**
19
     * @var int
20
     */
21
    private $limit;
22
    /**
23
     * @var int
24
     */
25
    private $perXSeconds;
26
27
    /**
28
     * CachePoolThrottle constructor.
29
     * @param CacheItemPoolInterface $cacheItemPool
30
     * @param int $limit
31
     * @param int $perXSeconds
32
     */
33 7
    public function __construct(CacheItemPoolInterface $cacheItemPool, int $limit = 60, int $perXSeconds = 60)
34
    {
35 7
        $this->cacheItemPool = $cacheItemPool;
36 7
        $this->limit = $limit;
37 7
        $this->perXSeconds = $perXSeconds;
38 7
    }
39
40
    /**
41
     * Returns true if the given request should be throttled in our implementation
42
     * @param \LunixREST\APIRequest\APIRequest $request
43
     * @return bool
44
     */
45 4
    public function shouldThrottle(APIRequest $request): bool
46
    {
47 4
        $item = $this->cacheItemPool->getItem($this->deriveCacheKey($request));
48
49 4
        return $item->get() >= $this->limit;
50
    }
51
52
    /**
53
     * Log that a request took place
54
     * @param \LunixREST\APIRequest\APIRequest $request
55
     */
56 2
    public function logRequest(APIRequest $request)
57
    {
58 2
        $item = $this->cacheItemPool->getItem($this->deriveCacheKey($request));
59
60 2
        if($requestCount = $item->get()) {
61 1
            $item->set($requestCount + 1);
62
        } else {
63 1
            $item->set(1)->expiresAfter($this->perXSeconds);
64
        }
65
66 2
        $this->cacheItemPool->save($item);
67 2
    }
68
69
    /**
70
     * @param APIRequest $request
71
     * @return string
72
     */
73
    protected abstract function deriveCacheKey(APIRequest $request): string;
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
74
75
    /**
76
     * @return CacheItemPoolInterface
77
     */
78 1
    public function getCacheItemPool(): CacheItemPoolInterface
79
    {
80 1
        return $this->cacheItemPool;
81
    }
82
}
83