CachePoolThrottle::getCacheItemPool()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
namespace LunixREST\Server\Throttle;
3
4
use LunixREST\Server\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\Server\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 15
    public function __construct(CacheItemPoolInterface $cacheItemPool, int $limit = 60, int $perXSeconds = 60)
34
    {
35 15
        $this->cacheItemPool = $cacheItemPool;
36 15
        $this->limit = $limit;
37 15
        $this->perXSeconds = $perXSeconds;
38 15
    }
39
40
    /**
41
     * Returns true if the given request should be throttled in our implementation
42
     * @param \LunixREST\Server\APIRequest\APIRequest $request
43
     * @return bool
44
     */
45 9
    public function shouldThrottle(APIRequest $request): bool
46
    {
47 9
        $item = $this->cacheItemPool->getItem($this->deriveCacheKey($request));
48
49 9
        return $item->get() >= $this->limit;
50
    }
51
52
    /**
53
     * Log that a request took place
54
     * @param \LunixREST\Server\APIRequest\APIRequest $request
55
     */
56 4
    public function logRequest(APIRequest $request): void
57
    {
58 4
        $item = $this->cacheItemPool->getItem($this->deriveCacheKey($request));
59
60 4
        if($requestCount = $item->get()) {
61 2
            $item->set($requestCount + 1);
62
        } else {
63 2
            $item->set(1)->expiresAfter($this->perXSeconds);
64
        }
65
66 4
        $this->cacheItemPool->save($item);
67 4
    }
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 2
    public function getCacheItemPool(): CacheItemPoolInterface
79
    {
80 2
        return $this->cacheItemPool;
81
    }
82
}
83