Passed
Push — master ( 353d8d...466fd2 )
by Hergen
12:11
created

IfMatch::handle()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 4
eloc 12
c 3
b 1
f 0
nc 3
nop 2
dl 0
loc 25
rs 9.8666
1
<?php
2
3
namespace Werk365\EtagConditionals\Middleware;
4
5
use Closure;
6
use Illuminate\Http\Request;
7
use Illuminate\Http\Resources\Json\JsonResource;
8
use Illuminate\Http\Response;
9
use Illuminate\Routing\Route;
10
11
class IfMatch extends Middleware
12
{
13
    public string $middleware = 'ifMatch';
14
15
    /**
16
     * Handle an incoming request.
17
     *
18
     * @param  \Illuminate\Http\Request  $request
19
     * @param  \Closure  $next
20
     * @return mixed
21
     */
22
    public function handle(Request $request, Closure $next)
23
    {
24
        // Next unless method is PATCH and If-Match header is set
25
        if (! ($request->isMethod('PATCH') && $request->hasHeader('If-Match'))) {
26
            return $next($request);
27
        }
28
29
        // Create new GET request to same endpoint,
30
        // copy headers and add header that allows you to ignore this request in middlewares
31
        $getRequest = Request::create($request->getRequestUri(), 'GET');
32
        $getRequest->headers = $request->headers;
33
        $getRequest->headers->set('X-Skip-Middleware', true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type string|string[] expected by parameter $values of Symfony\Component\HttpFoundation\HeaderBag::set(). ( Ignorable by Annotation )

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

33
        $getRequest->headers->set('X-Skip-Middleware', /** @scrutinizer ignore-type */ true);
Loading history...
34
        $getResponse = app()->handle($getRequest);
0 ignored issues
show
introduced by
The method handle() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

34
        $getResponse = app()->/** @scrutinizer ignore-call */ handle($getRequest);
Loading history...
35
36
        // Get content from response object and get hashes from content and etag
37
        $getContent = $getResponse->getContent();
38
        $getEtag = '"'.md5($getContent).'"';
39
        $ifMatch = $request->header('If-Match');
40
41
        // Compare current and request hashes
42
        if ($getEtag !== $ifMatch) {
43
            return response(null, 412);
44
        }
45
46
        return $next($request);
47
    }
48
}
49