Completed
Push — master ( 0faaef...a96626 )
by Nikola
02:09
created

AbstractRateLimiter   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 87
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 1
dl 0
loc 87
ccs 23
cts 23
cp 1
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getLimit() 0 4 1
A getWindow() 0 4 1
A hit() 0 15 3
A getRemainingAttempts() 0 4 1
A getResetAt() 0 4 1
A getCurrent() 0 4 1
get() 0 1 ?
init() 0 1 ?
increment() 0 1 ?
ttl() 0 1 ?
1
<?php
2
/**
3
 * This file is part of the Rate Limit package.
4
 *
5
 * Copyright (c) Nikola Posa
6
 *
7
 * For full copyright and license information, please refer to the LICENSE file,
8
 * located at the package root folder.
9
 */
10
11
declare(strict_types=1);
12
13
namespace RateLimit;
14
15
use RateLimit\Exception\RateLimitExceededException;
16
17
/**
18
 * @author Nikola Posa <[email protected]>
19
 */
20
abstract class AbstractRateLimiter implements RateLimiterInterface
21
{
22
    /**
23
     * @var int
24
     */
25
    protected $limit;
26
27
    /**
28
     * @var int
29
     */
30
    protected $window;
31
32
    /**
33
     * @var string
34
     */
35
    protected $key;
36
37 24
    public function __construct(int $limit, int $window)
38
    {
39 24
        $this->limit = $limit;
40 24
        $this->window = $window;
41 24
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 8
    public function getLimit() : int
47
    {
48 8
        return $this->limit;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 2
    public function getWindow() : int
55
    {
56 2
        return $this->window;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62 14
    public function hit(string $key)
63
    {
64 14
        $current = $this->getCurrent($key);
65
66 14
        if ($current >= $this->limit) {
67 7
            throw RateLimitExceededException::forKey($key);
68
        }
69
70 14
        if (0 === $current) {
71 14
            $this->init($key);
72 14
            return;
73
        }
74
75 1
        $this->increment($key);
76 1
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81 10
    public function getRemainingAttempts(string $key) : int
82
    {
83 10
        return max(0, $this->limit - $this->getCurrent($key));
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89 10
    public function getResetAt(string $key) : int
90
    {
91 10
        return time() + $this->ttl($key);
92
    }
93
94 14
    protected function getCurrent(string $key) : int
95
    {
96 14
        return $this->get($key, 0);
97
    }
98
99
    abstract protected function get(string $key, int $default) : int;
100
101
    abstract protected function init(string $key);
102
103
    abstract protected function increment(string $key);
104
105
    abstract protected function ttl(string $key) : int;
106
}
107