Passed
Push — master ( 91b62f...022aa2 )
by Henri
01:21
created

MiddlewareTrait::executeMiddleware()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
nc 6
nop 1
dl 0
loc 16
c 0
b 0
f 0
cc 4
rs 10
1
<?php
2
3
namespace HnrAzevedo\Router;
4
5
use Exception;
6
use HnrAzevedo\Http\ServerRequest;
7
use HnrAzevedo\Http\Uri;
8
use HnrAzevedo\Http\Factory;
9
10
trait MiddlewareTrait{
11
    protected array $middlewares = [];
12
    protected RequestHandler $request;
13
    protected ServerRequest $serverRequest;
14
15
    protected function executeMiddleware(array $route)
16
    {
17
        $this->request = new RequestHandler($route['protocol'],new Uri($this->host.$route['url']));  
0 ignored issues
show
Unused Code introduced by
The call to HnrAzevedo\Router\RequestHandler::__construct() has too many arguments starting with $route['protocol']. ( Ignorable by Annotation )

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

17
        $this->request = /** @scrutinizer ignore-call */ new RequestHandler($route['protocol'],new Uri($this->host.$route['url']));  

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...
18
        $this->serverRequest = (new Factory())->createServerRequest($route['protocol'],new Uri($this->host.$route['url'])); 
19
20
        $middlewares = (is_array($route['middlewares'])) ? $route['middlewares'] : [ $route['middlewares'] ];
21
22
        foreach($middlewares as $middleware){
23
            if(is_null($middleware)){
24
                continue;
25
            }
26
27
            $this->middlewareHandle($middleware);
28
        }
29
30
        return $this;
31
    }
32
33
    protected function middlewareHandle(string $m)
34
    {
35
        $middleware = $this->middlewareExists($m);
36
        return $middleware->process($this->serverRequest, $this->request);
37
    }
38
39
    protected function middlewareExists(string $m)
40
    {
41
        if(class_exists(str_replace('::class','',$m))){
42
            $m = str_replace('::class','',$m);
43
            return new $m();
44
        }
45
46
        if(array_key_exists($m,$this->middlewares)){
47
            return new $this->middlewares[$m]();
48
        }
49
50
        throw new Exception("Middleware {$m} not found.");
51
    }
52
53
}
54