Completed
Pull Request — master (#10)
by Krishnaprasad
08:08 queued 03:56
created

FixedWindowThrottler::count()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 14
Code Lines 8

Duplication

Lines 14
Ratio 100 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 14
loc 14
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 5
nop 0
crap 3
1
<?php
2
/**
3
 * The MIT License (MIT)
4
 *
5
 * Copyright (c) 2015 Krishnaprasad MG <[email protected]>
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in all
15
 * copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
 * SOFTWARE.
24
 */
25
26
namespace Sunspikes\Ratelimit\Throttle\Throttler;
27
28
use Sunspikes\Ratelimit\Cache\Exception\ItemNotFoundException;
29
use Sunspikes\Ratelimit\Throttle\Entity\CacheTime;
30
use Sunspikes\Ratelimit\Throttle\Entity\CacheCount;
31
32
final class FixedWindowThrottler extends AbstractWindowThrottler implements RetriableThrottlerInterface
33
{
34
    const CACHE_KEY_TIME = '-time';
35
    const CACHE_KEY_HITS = '-hits';
36
37
    /**
38
     * @var int|null
39
     */
40
    private $hitCount;
41
42
    /**
43
     * @inheritdoc
44
     */
45 11
    public function hit()
46
    {
47 11
        $this->setCachedHitCount($this->count() + 1);
48 11
        $item = new CacheTime($this->timeProvider->now(), $this->cacheTtl);
49
        // Update the window start time if the previous window has passed, or no cached window exists
50
        try {
51
            /** @var CacheTime $currentItem */
52 11
            $currentItem = $this->cache->getItem($this->getTimeCacheKey());
53 9
            if (($this->timeProvider->now() - $currentItem->getTime()) > $this->timeLimit) {
54 9
                $this->cache->setItem($this->getTimeCacheKey(), $item);
55
            }
56 11
        } catch (ItemNotFoundException $exception) {
57 11
            $this->cache->setItem($this->getTimeCacheKey(), $item);
58
        }
59
60 11
        return $this;
61
    }
62
63
    /**
64
     * @inheritdoc
65
     */
66 11 View Code Duplication
    public function count()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
67
    {
68
        try {
69
            /** @var CacheTime $currentItem */
70 11
            $currentItem = $this->cache->getItem($this->getTimeCacheKey());
71 11
            if (($this->timeProvider->now() - $currentItem->getTime()) > $this->timeLimit) {
72 1
                return 0;
73
            }
74
75 11
            return $this->getCachedHitCount();
76 11
        } catch (ItemNotFoundException $exception) {
77 11
            return 0;
78
        }
79
    }
80
81
    /**
82
     * @inheritdoc
83
     */
84 2
    public function clear()
85
    {
86 2
        $this->setCachedHitCount(0);
87 2
        $item = new CacheTime($this->timeProvider->now(), $this->cacheTtl);
88 2
        $this->cache->setItem($this->getTimeCacheKey(), $item);
89 2
    }
90
91
    /**
92
     * @inheritdoc
93
     */
94 5 View Code Duplication
    public function getRetryTimeout()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
    {
96 5
        if ($this->check()) {
97 5
            return 0;
98
        }
99
100
        // Return the time until the current window ends
101
        // Try/catch for the ItemNotFoundException is not required, in that case $this->check() will return true
102
        /** @var CacheTime $cachedTime */
103 1
        $cachedTime = $this->cache->getItem($this->getTimeCacheKey());
104
105 1
        return self::SECOND_TO_MILLISECOND_MULTIPLIER * ($this->timeLimit - $this->timeProvider->now() + $cachedTime->getTime());
106
    }
107
108
    /**
109
     * @return int
110
     *
111
     * @throws ItemNotFoundException
112
     */
113 11
    private function getCachedHitCount()
114
    {
115 11
        if (null !== $this->hitCount) {
116 11
            return $this->hitCount;
117
        }
118
        /** @var CacheCount $item */
119
        $item = $this->cache->getItem($this->getHitsCacheKey());
120
121
        return $item->getCount();
122
    }
123
124
    /**
125
     * @param int $hitCount
126
     */
127 11
    private function setCachedHitCount($hitCount)
128
    {
129 11
        $this->hitCount = $hitCount;
130 11
        $item = new CacheCount($hitCount, $this->cacheTtl);
131 11
        $this->cache->setItem($this->getHitsCacheKey(), $item);
132 11
    }
133
134
    /**
135
     * @return string
136
     */
137 11
    private function getHitsCacheKey()
138
    {
139 11
        return $this->key . self::CACHE_KEY_HITS;
140
    }
141
142
    /**
143
     * @return string
144
     */
145 11
    private function getTimeCacheKey()
146
    {
147 11
        return $this->key . self::CACHE_KEY_TIME;
148
    }
149
}
150