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

createOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
crap 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