Completed
Pull Request — master (#2)
by Nikola
01:44
created

createRedisBackedRateLimiter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
crap 2
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
    const DEFAULT_WINDOW = 15 * 60;
30
31 6
    public static function createInMemoryRateLimiter(array $options = []) : RequestsPerWindowRateLimiter
32
    {
33 6
        return new RequestsPerWindowRateLimiter(
34 6
            new InMemoryStorage(),
35 6
            new IpAddressIdentityResolver(),
36 6
            self::createOptions($options)
37
        );
38
    }
39
40
    public static function createRedisBackedRateLimiter(array $options = []) : RequestsPerWindowRateLimiter
41
    {
42
        return new RequestsPerWindowRateLimiter(
43
            new RedisStorage(new Redis()),
44
            new IpAddressIdentityResolver(),
45
            self::createOptions($options)
46
        );
47
    }
48
49 6
    public static function createOptions(array $options = []) : RequestsPerWindowOptions
50
    {
51 6
        $options = array_merge(self::getDefaultOptions(), $options);
52
53 6
        return new RequestsPerWindowOptions(
54 6
            $options['limit'],
55 6
            $options['window'],
56 6
            $options['limitExceededHandler']
57
        );
58
    }
59 6
    private static function getDefaultOptions() : array
60
    {
61
        return [
62 6
            'limit' => self::DEFAULT_LIMIT,
63 6
            'window' => self::DEFAULT_WINDOW,
64 6
            'limitExceededHandler' => function (RequestInterface $request, ResponseInterface $response) {
65 2
                return $response;
66 6
            },
67
        ];
68
    }
69
}
70