-
Notifications
You must be signed in to change notification settings - Fork 0
/
RateLimiterSubscriber.php
44 lines (37 loc) · 1.55 KB
/
RateLimiterSubscriber.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\RateLimiter\RateLimiterFactory;
class RateLimiterSubscriber implements EventSubscriberInterface
{
public function __construct(private RateLimiterFactory $authenticatedApiLimiter)
{
}
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event): void {
$request = $event->getRequest();
// Apply to all api routes except index
if($request->get("_route") !== 'api_index' && str_contains($request->get("_route"), 'api_')) {
$limiter = $this->authenticatedApiLimiter->create($request->getClientIp());
$limit = $limiter->consume();
//if (false === $limiter->consume(1)->isAccepted()) {
if (false === $limit->isAccepted()) {
//throw new TooManyRequestsHttpException();
$headers = [
'X-RateLimit-Remaining' => $limit->getRemainingTokens(),
'X-RateLimit-Retry-After' => $limit->getRetryAfter()->getTimestamp(),
'X-RateLimit-Limit' => $limit->getLimit(),
];
$response = new Response(null, Response::HTTP_TOO_MANY_REQUESTS, $headers);
$event->setResponse($response);
}
}
}
}