|
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
|
|
|
|