Completed
Pull Request — master (#9)
by
unknown
07:46
created

AbstractRateLimiter::setLimit()   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 8
    public function setLimit(int $limit)
47
    {
48 8
        $this->limit = $limit;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 2
    public function getLimit() : int
55
    {
56 2
        return $this->limit;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62 14
    public function getWindow() : int
63
    {
64 14
        return $this->window;
65
    }
66 14
67 7
    /**
68
     * {@inheritdoc}
69
     */
70 14
    public function hit(string $key)
71 14
    {
72 14
        $current = $this->getCurrent($key);
73
74
        if ($current >= $this->limit) {
75 1
            throw RateLimitExceededException::forKey($key);
76 1
        }
77
78
        if (0 === $current) {
79
            $this->init($key);
80
            return;
81 10
        }
82
83 10
        $this->increment($key);
84
    }
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 14
    /**
95
     * {@inheritdoc}
96 14
     */
97
    public function getResetAt(string $key) : int
98
    {
99
        return (int)ceil(microtime(true) + $this->ttl($key));
100
    }
101
102
    protected function getCurrent(string $key) : int
103
    {
104
        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) : float;
114
}
115