Completed
Pull Request — master (#11)
by
unknown
12:23
created

RateLimitHandler::isRateLimitExceeded()   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
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
/*
4
 * This file is part of the ApiRateLimitBundle
5
 *
6
 * (c) Indra Gunawan <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Indragunawan\ApiRateLimitBundle\Service;
13
14
use Doctrine\Common\Annotations\AnnotationReader;
15
use Indragunawan\ApiRateLimitBundle\Annotation\ApiRateLimit;
16
use Psr\Cache\CacheItemPoolInterface;
17
use ReflectionClass;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
20
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
21
22
/**
23
 * @author Indra Gunawan <[email protected]>
24
 */
25
class RateLimitHandler
26
{
27
    /**
28
     * @var CacheItemPoolInterface
29
     */
30
    private $cacheItemPool;
31
32
    /**
33
     * @var TokenStorageInterface
34
     */
35
    private $tokenStorage;
36
37
    /**
38
     * @var AuthorizationCheckerInterface
39
     */
40
    private $authorizationChecker;
41
42
    /**
43
     * @var array
44
     */
45
    private $throttleConfig;
46
47
    /**
48
     * @var int
49
     */
50
    private $limit;
51
52
    /**
53
     * @var int
54
     */
55
    private $remaining;
56
57
    /**
58
     * @var int
59
     */
60
    private $reset;
61
62
    /**
63
     * @var
64
     */
65
    private $enabled = true;
66
67
    /**
68
     * @var bool
69
     */
70
    private $rateLimitExceeded = false;
71
72
    /**
73
     * RateLimitHandler constructor.
74
     *
75
     * @param CacheItemPoolInterface $cacheItemPool
76
     * @param TokenStorageInterface $tokenStorage
77
     * @param AuthorizationCheckerInterface $authorizationChecker
78
     * @param array $throttleConfig
79
     */
80 8
    public function __construct(
81
        CacheItemPoolInterface $cacheItemPool,
82
        TokenStorageInterface $tokenStorage,
83
        AuthorizationCheckerInterface $authorizationChecker,
84
        array $throttleConfig
85
    ) {
86 8
        $this->cacheItemPool = $cacheItemPool;
87 8
        $this->tokenStorage = $tokenStorage;
88 8
        $this->authorizationChecker = $authorizationChecker;
89 8
        $this->throttleConfig = $throttleConfig;
90 8
    }
91
92
    /**
93
     * @return bool
94
     */
95 8
    public function isEnabled()
96
    {
97 8
        return $this->enabled;
98
    }
99
100
    /**
101
     * @return bool
102
     */
103 5
    public function isRateLimitExceeded()
104
    {
105 5
        return $this->rateLimitExceeded;
106
    }
107
108
    /**
109
     * @return array
110
     */
111 7
    public function getRateLimitInfo(): array
112
    {
113
        return [
114 7
            'limit'     => $this->limit,
115 7
            'remaining' => $this->remaining,
116 7
            'reset'     => $this->reset,
117
        ];
118
    }
119
120
    /**
121
     * @param string $ip
122
     * @param string|null $username
123
     * @param string|null $userRole
124
     *
125
     * @return string
126
     */
127 8
    public static function generateCacheKey(string $ip, string $username = null, string $userRole = null): string
128
    {
129 8
        if (!empty($username) && !empty($userRole)) {
130 2
            return sprintf('_api_rate_limit_metadata$%s', sha1($userRole . $username));
131
        }
132
133 6
        return sprintf('_api_rate_limit_metadata$%s', sha1($ip));
134
    }
135
136
    /**
137
     * @param Request $request
138
     *
139
     * @throws \Doctrine\Common\Annotations\AnnotationException
140
     * @throws \Psr\Cache\InvalidArgumentException
141
     * @throws \ReflectionException
142
     */
143 8
    public function handle(Request $request)
144
    {
145 8
        $annotationReader = new AnnotationReader();
146
        /** @var ApiRateLimit $annotation */
147 8
        $annotation = $annotationReader->getClassAnnotation(
148 8
            new ReflectionClass($request->attributes->get('_api_resource_class')),
149 8
            ApiRateLimit::class
150
        );
151
152 8
        if (null !== $annotation) {
153 8
            $this->enabled = $annotation->enabled;
154
        } else {
155
	    $annotation = new ApiRateLimit();
156
	}
157
158 8
        list($key, $limit, $period) = $this->getThrottle($request, $annotation);
159
160 8
        if ($this->enabled) {
161 7
            $this->decreaseRateLimitRemaining($key, $limit, $period);
162
        }
163 8
    }
164
165
    /**
166
     * @param string $key
167
     * @param int $limit
168
     * @param int $period
169
     *
170
     * @throws \Psr\Cache\InvalidArgumentException
171
     */
172 7
    protected function decreaseRateLimitRemaining(string $key, int $limit, int $period)
173
    {
174 7
        $cost = 1;
175 7
        $currentTime = gmdate('U');
176
177 7
        $rateLimitInfo = $this->cacheItemPool->getItem($key);
178 7
        $rateLimit = $rateLimitInfo->get();
179 7
        if ($rateLimitInfo->isHit() && $currentTime <= $rateLimit['reset']) {
180
            // decrease existing rate limit remaining
181 2
            if ($rateLimit['remaining'] - $cost >= 0) {
182 1
                $remaining = $rateLimit['remaining'] - $cost;
183 1
                $reset = $rateLimit['reset'];
184 1
                $ttl = $rateLimit['reset'] - $currentTime;
185
            } else {
186 1
                $this->rateLimitExceeded = true;
187 1
                $this->reset = $rateLimit['reset'];
188 1
                $this->limit = $limit;
189 1
                $this->remaining = 0;
190
191 2
                return;
192
            }
193
        } else {
194
            // add / reset new rate limit remaining
195 5
            $remaining = $limit - $cost;
196 5
            $reset = $currentTime + $period;
197 5
            $ttl = $period;
198
        }
199
200
        $rateLimit = [
201 6
            'limit' => $limit,
202 6
            'remaining' => $remaining,
203 6
            'reset' => $reset,
204
        ];
205
206 6
        $rateLimitInfo->set($rateLimit);
207 6
        $rateLimitInfo->expiresAfter($ttl);
208
209 6
        $this->cacheItemPool->save($rateLimitInfo);
210
211 6
        $this->limit = $limit;
212 6
        $this->remaining = $remaining;
0 ignored issues
show
Documentation Bug introduced by
It seems like $remaining can also be of type double. However, the property $remaining is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
213 6
        $this->reset = $reset;
214 6
    }
215
216
    /**
217
     * @param Request $request
218
     *
219
     * @return array
220
     */
221 8
    private function getThrottle(Request $request, ApiRateLimit $annotation)
222
    {
223 8
        if (null !== $token = $this->tokenStorage->getToken()) {
224
            // no anonymous
225 2
            if (is_object($token->getUser())) {
226 2
                $rolesConfig = $this->throttleConfig['roles'];
227 2
                if (!empty($annotation->throttle['roles'])) {
228 1
                    $rolesConfig = $annotation->throttle['roles'];
229
                }
230
231 2
                foreach ($rolesConfig as $role => $throttle) {
232 2
                    if ($this->authorizationChecker->isGranted($role)) {
233 2
                        $username = $token->getUsername();
234 2
                        $userRole = $role;
235 2
                        $limit = $throttle['limit'];
236 2
                        $period = $throttle['period'];
237
238 2
                        return [self::generateCacheKey($request->getClientIp(), $username, $userRole), $limit, $period];
239
                    }
240
                }
241
            }
242
        }
243
244 6
        if (!empty($annotation->throttle['default'])) {
245 1
            $limit = $annotation->throttle['default']['limit'];
246 1
            $period = $annotation->throttle['default']['period'];
247
        } else {
248 5
            $limit = $this->throttleConfig['default']['limit'];
249 5
            $period = $this->throttleConfig['default']['period'];
250
        }
251
252 6
        return [self::generateCacheKey($request->getClientIp()), $limit, $period];
253
    }
254
}
255