Completed
Pull Request — master (#12)
by
unknown
12:17 queued 02:05
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
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
    public function __construct(int $limit, int $window)
38
    {
39
        $this->limit = $limit;
40
        $this->window = $window;
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function getLimit() : int
47
    {
48
        return $this->limit;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function getWindow() : int
55
    {
56
        return $this->window;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function hit(string $key)
63
    {
64
        $current = $this->getCurrent($key);
65
66
        if ($current >= $this->limit) {
67
            throw RateLimitExceededException::forKey($key);
68
        }
69
70
        if (0 === $current) {
71
            $this->init($key);
72
            return;
73
        }
74
75
        $this->increment($key);
76
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81
    public function getRemainingAttempts(string $key) : int
82
    {
83
        return max(0, $this->limit - $this->getCurrent($key));
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89
    public function getResetAt(string $key) : int
90
    {
91
        return (int)ceil(microtime(true) + $this->ttl($key))
92
    }
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected '}', expecting ';'
Loading history...
93
94
    protected function getCurrent(string $key) : int
95
    {
96
        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) : float;
106
}
107