Passed
Push — master ( 81da44...a02115 )
by Henri
01:33
created

MiddlewareTrait::middlewareExists()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 6
nc 3
nop 1
dl 0
loc 12
c 1
b 0
f 1
cc 3
rs 10
1
<?php
2
3
namespace HnrAzevedo\Router;
4
5
use Exception;
6
7
trait MiddlewareTrait{
8
    protected array $middlewares = [];
9
10
    protected function checkMiddleware(array $route)
11
    {
12
        $middlewares = (is_array($route['middlewares'])) ? $route['middlewares'] : [ $route['middlewares'] ];
13
14
        foreach($middlewares as $middleware){
15
            if(is_null($middleware)){
16
                continue;
17
            }
18
19
            $this->middlewareHandle($middleware);
20
        }
21
22
        return $this;
23
    }
24
25
    protected function middlewareHandle(string $m)
26
    {
27
        $middleware = $this->middlewareExists($m);
28
        $middleware->process($this->serverRequest,$this->request);
29
    }
30
31
    protected function middlewareExists(string $m)
32
    {
33
        if(class_exists(str_replace('::class','',$m))){
34
            $m = str_replace('::class','',$m);
35
            return new $m();
36
        }
37
38
        if(array_key_exists($m,$this->middlewares)){
39
            return new $this->middlewares[$m]();
40
        }
41
42
        throw new Exception("Middleware {$m} not found.");
43
    }
44
45
}
46