ApiActionRateLimiter   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 41
rs 10
c 0
b 0
f 0
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A resolveKey() 0 5 1
A handle() 0 24 2
A resolveMaxAttempts() 0 3 1
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
Unused Code introduced by
The call to config() has too many arguments starting with config('blog-core.blog_api_default_rate_limit'). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

51
        return (int) /** @scrutinizer ignore-call */ config("blog-core.rate_limits.{$name}", config('blog-core.blog_api_default_rate_limit'));

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.

Loading history...
52
    }
53
}
54