Completed
Push — master ( 493066...872ff9 )
by Nikola
01:43
created

RequestsPerWindowRateLimiterFactory   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 77.27%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 5
dl 0
loc 44
ccs 17
cts 22
cp 0.7727
rs 10
c 0
b 0
f 0

4 Methods

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