|
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\Options\RequestsPerWindowOptions; |
|
16
|
|
|
use Psr\Http\Message\RequestInterface; |
|
17
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
18
|
|
|
use RateLimit\Identity\IpAddressIdentityResolver; |
|
19
|
|
|
use RateLimit\Storage\InMemoryStorage; |
|
20
|
|
|
use RateLimit\Storage\RedisStorage; |
|
21
|
|
|
use Redis; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @author Nikola Posa <[email protected]> |
|
25
|
|
|
*/ |
|
26
|
|
|
final class RequestsPerWindowRateLimiterFactory |
|
27
|
|
|
{ |
|
28
|
|
|
const DEFAULT_LIMIT = 100; |
|
29
|
6 |
|
const DEFAULT_WINDOW = 15 * 60; |
|
30
|
|
|
|
|
31
|
6 |
|
public static function createInMemoryRateLimiter(array $options = []) : RequestsPerWindowRateLimiter |
|
32
|
6 |
|
{ |
|
33
|
6 |
|
return new RequestsPerWindowRateLimiter( |
|
34
|
6 |
|
new InMemoryStorage(), |
|
35
|
|
|
new IpAddressIdentityResolver(), |
|
36
|
|
|
self::createOptions($options) |
|
37
|
|
|
); |
|
38
|
6 |
|
} |
|
39
|
|
|
|
|
40
|
6 |
|
public static function createRedisBackedRateLimiter(array $options = []) : RequestsPerWindowRateLimiter |
|
41
|
|
|
{ |
|
42
|
6 |
|
return new RequestsPerWindowRateLimiter( |
|
43
|
6 |
|
new RedisStorage(new Redis()), |
|
44
|
6 |
|
new IpAddressIdentityResolver(), |
|
45
|
6 |
|
self::createOptions($options) |
|
46
|
|
|
); |
|
47
|
|
|
} |
|
48
|
6 |
|
|
|
49
|
|
|
public static function createOptions(array $options = []) : RequestsPerWindowOptions |
|
50
|
|
|
{ |
|
51
|
6 |
|
$options = array_merge(self::getDefaultOptions(), $options); |
|
52
|
6 |
|
|
|
53
|
6 |
|
return new RequestsPerWindowOptions( |
|
54
|
2 |
|
$options['limit'], |
|
55
|
6 |
|
$options['window'], |
|
56
|
|
|
$options['limitExceededHandler'] |
|
57
|
|
|
); |
|
58
|
|
|
} |
|
59
|
|
|
private static function getDefaultOptions() : array |
|
60
|
|
|
{ |
|
61
|
|
|
return [ |
|
62
|
|
|
'limit' => self::DEFAULT_LIMIT, |
|
63
|
|
|
'window' => self::DEFAULT_WINDOW, |
|
64
|
|
|
'limitExceededHandler' => function (RequestInterface $request, ResponseInterface $response) { |
|
65
|
|
|
return $response; |
|
66
|
|
|
}, |
|
67
|
|
|
]; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|