AbstractRateLimiter::getWindow()   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
/**
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
namespace RateLimit;
12
13
use RateLimit\Exception\RateLimitExceededException;
14
15
/**
16
 * @author Nikola Posa <[email protected]>
17
 */
18
abstract class AbstractRateLimiter implements RateLimiterInterface
19
{
20
    /**
21
     * @var int
22
     */
23
    protected $limit;
24
25
    /**
26
     * @var int
27
     */
28
    protected $window;
29
30
    /**
31
     * @var string
32
     */
33
    protected $key;
34
35 24
    public function __construct($limit, $window)
36
    {
37 24
        $this->limit = (int)$limit;
38 24
        $this->window = (int)$window;
39 24
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 8
    public function getLimit()
45
    {
46 8
        return $this->limit;
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52 2
    public function getWindow()
53
    {
54 2
        return $this->window;
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60 14
    public function hit($key)
61
    {
62 14
        $key = (string)$key;
63 14
        $current = $this->getCurrent($key);
64
65 14
        if ($current >= $this->limit) {
66 7
            throw RateLimitExceededException::forKey($key);
67
        }
68
69 14
        if (0 === $current) {
70 14
            $this->init($key);
71 14
            return;
72
        }
73
74 1
        $this->increment($key);
75 1
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 10
    public function getRemainingAttempts($key)
81
    {
82 10
        return max(0, $this->limit - $this->getCurrent((string)$key));
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88 10
    public function getResetAt($key)
89
    {
90 10
        return time() + $this->ttl((string)$key);
91
    }
92
93 14
    protected function getCurrent($key)
94
    {
95 14
        return $this->get((string)$key, 0);
96
    }
97
98
    abstract protected function get($key, $default);
99
100
    abstract protected function init($key);
101
102
    abstract protected function increment($key);
103
104
    abstract protected function ttl($key);
105
}
106