RateLimiterMiddleware   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 18
c 1
b 0
f 0
dl 0
loc 39
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A perMinute() 0 10 1
A __invoke() 0 5 1
A perSecond() 0 10 1
1
<?php
2
3
namespace Asiadevmedia\GuzzleRateLimiter;
4
5
use Psr\Http\Message\RequestInterface;
6
7
class RateLimiterMiddleware
8
{
9
    /** @var \Asiadevmedia\GuzzleRateLimiter\RateLimiter */
10
    protected $rateLimiter;
11
12
    private function __construct(RateLimiter $rateLimiter)
13
    {
14
        $this->rateLimiter = $rateLimiter;
15
    }
16
17
    public static function perSecond(int $limit, Store $store = null, Deferrer $deferrer = null): RateLimiterMiddleware
18
    {
19
        $rateLimiter = new RateLimiter(
20
            $limit,
21
            RateLimiter::TIME_FRAME_SECOND,
22
            $store ?? new InMemoryStore(),
23
            $deferrer ?? new SleepDeferrer()
24
        );
25
26
        return new static($rateLimiter);
27
    }
28
29
    public static function perMinute(int $limit, Store $store = null, Deferrer $deferrer = null): RateLimiterMiddleware
30
    {
31
        $rateLimiter = new RateLimiter(
32
            $limit,
33
            RateLimiter::TIME_FRAME_MINUTE,
34
            $store ?? new InMemoryStore(),
35
            $deferrer ?? new SleepDeferrer()
36
        );
37
38
        return new static($rateLimiter);
39
    }
40
41
    public function __invoke(callable $handler)
42
    {
43
        return function (RequestInterface $request, array $options) use ($handler) {
44
            return $this->rateLimiter->handle(function () use ($request, $handler, $options) {
45
                return $handler($request, $options);
46
            });
47
        };
48
    }
49
}
50