cslant /
blog-api-package
| 1 | <?php |
||
| 2 | |||
| 3 | namespace CSlant\Blog\Api\Http\Middlewares; |
||
| 4 | |||
| 5 | use Closure; |
||
| 6 | use Illuminate\Http\JsonResponse; |
||
| 7 | use Illuminate\Http\Request; |
||
| 8 | use Illuminate\Http\Response; |
||
| 9 | use Illuminate\Support\Facades\RateLimiter; |
||
| 10 | |||
| 11 | class ApiActionRateLimiter |
||
| 12 | { |
||
| 13 | /** |
||
| 14 | * Handle an incoming request with configurable rate limiting. |
||
| 15 | */ |
||
| 16 | public function handle(Request $request, Closure $next, string $name): Response|JsonResponse |
||
| 17 | { |
||
| 18 | $key = $this->resolveKey($request, $name); |
||
| 19 | $maxAttempts = $this->resolveMaxAttempts($name); |
||
| 20 | |||
| 21 | if (RateLimiter::tooManyAttempts($key, $maxAttempts)) { |
||
| 22 | return response()->json([ |
||
| 23 | 'error' => true, |
||
| 24 | 'message' => 'Too many attempts. Please try again later.', |
||
| 25 | 'maxAttempts' => $maxAttempts, |
||
| 26 | ], 429); |
||
| 27 | } |
||
| 28 | |||
| 29 | RateLimiter::hit($key); |
||
| 30 | |||
| 31 | /** @var Response $response */ |
||
| 32 | $response = $next($request); |
||
| 33 | |||
| 34 | $response->headers->add([ |
||
| 35 | 'X-RateLimit-Limit' => $maxAttempts, |
||
| 36 | 'X-RateLimit-Remaining' => RateLimiter::remaining($key, $maxAttempts), |
||
| 37 | ]); |
||
| 38 | |||
| 39 | return $response; |
||
| 40 | } |
||
| 41 | |||
| 42 | private function resolveKey(Request $request, string $prefix): string |
||
| 43 | { |
||
| 44 | $identifier = $request->user()->id ?? $request->ip(); |
||
| 45 | |||
| 46 | return "{$prefix}:{$identifier}"; |
||
| 47 | } |
||
| 48 | |||
| 49 | private function resolveMaxAttempts(string $name): int |
||
| 50 | { |
||
| 51 | return (int) config("blog-core.rate_limits.{$name}", config('blog-core.blog_api_default_rate_limit')); |
||
|
0 ignored issues
–
show
|
|||
| 52 | } |
||
| 53 | } |
||
| 54 |
This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.
If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.