Completed
Pull Request — master (#13)
by
unknown
21:01 queued 09:03
created

AbstractRateLimiter::getCurrent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

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
nc 1
nop 1
crap 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
    public function setLimit(int $limit)
47
    {
48
        $this->limit = $limit;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 8
    public function getLimit() : int
55
    {
56 8
        return $this->limit;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62 2
    public function getWindow() : int
63
    {
64 2
        return $this->window;
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70 14
    public function hit(string $key)
71
    {
72 14
        $current = $this->getCurrent($key);
73
74 14
        if ($current >= $this->limit) {
75 7
            throw RateLimitExceededException::forKey($key);
76
        }
77
78 14
        if (0 === $current) {
79 14
            $this->init($key);
80 14
            return;
81
        }
82
83 1
        $this->increment($key);
84 1
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89 10
    public function getRemainingAttempts(string $key) : int
90
    {
91 10
        return max(0, $this->limit - $this->getCurrent($key));
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97 10
    public function getResetAt(string $key) : int
98
    {
99 10
        return time() + $this->ttl($key);
100
    }
101
102 14
    protected function getCurrent(string $key) : int
103
    {
104 14
        return $this->get($key, 0);
105
    }
106
107
    abstract protected function get(string $key, int $default) : int;
108
109
    abstract protected function init(string $key);
110
111
    abstract protected function increment(string $key);
112
113
    abstract protected function ttl(string $key) : int;
114
}
115