Passed
Branch v2-dev (b2175f)
by Henri
01:32
created

MiddlewareTrait.php$0 ➔ handleMiddlewares()   A

Complexity

Conditions 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A MiddlewareTrait.php$0 ➔ handle() 0 3 1
1
<?php
2
3
namespace HnrAzevedo\Router;
4
5
use HnrAzevedo\Http\Factory;
6
use HnrAzevedo\Http\ServerRequest;
7
use HnrAzevedo\Http\Response;
8
use Psr\Http\Server\RequestHandlerInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
12
trait MiddlewareTrait
13
{
14
    use Helper;
15
16
    protected array $globalMiddlewares = [];
17
    protected ServerRequest $serverRequest;
18
    protected array $currentMiddlewares = [];
19
20
    public static function globalMiddlewares(array $middlewares): RouterInterface
21
    {
22
        foreach($middlewares as $middleware){
23
            if(!class_exists($middleware)){
24
                throw new \RuntimeException("Middleware class {$middleware} not exists");
25
            }
26
        }
27
        self::getInstance()->setGlobalMiddlewares($middlewares);
28
        return self::getInstance();
29
    }
30
31
    protected function setGlobalMiddlewares(array $middlewares): void
32
    {
33
        $this->globalMiddlewares = $middlewares;
34
    }
35
36
    public static function middleware($middlewares): RouterInterface
37
    {
38
        $middlewares = (is_array($middlewares)) ? $middlewares : [ $middlewares ];
39
        $route = self::getInstance()->inSave();
40
        $route['middlewares'] = (is_array($route['middlewares'])) ? array_merge($route['middlewares'],$middlewares) : $middlewares;
41
        self::getInstance()->updateRoute($route,array_key_last(self::getInstance()->getRoutes()));
42
        return self::getInstance();
43
    }
44
45
    private static function existMiddleware(string $name): void
46
    {
47
        if(!class_exists($name) && !array_key_exists($name,self::$globalMiddlewares)){
48
            throw new \RuntimeException("Middleware {$name} does not exist");
49
        }
50
    }
51
52
    protected function handleMiddlewares(): void
53
    {
54
        $factory = new Factory();
55
56
        $this->serverRequest = (!isset($this->serverRequest)) ? $factory->createServerRequest($_SERVER['REQUEST_METHOD'], $this->current()['uri'],['route' => $this->current()]) : $this->serverRequest;
0 ignored issues
show
Bug introduced by
It seems like current() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

56
        $this->serverRequest = (!isset($this->serverRequest)) ? $factory->createServerRequest($_SERVER['REQUEST_METHOD'], $this->/** @scrutinizer ignore-call */ current()['uri'],['route' => $this->current()]) : $this->serverRequest;
Loading history...
57
        
58
        foreach ($this->current()['middlewares'] as $middleware){
59
            $this->currentMiddlewares[] = (class_exists($middleware)) ? new $middleware() : new $this->globalMiddlewares[$middleware]();
60
        }
61
62
        $this->process($this->serverRequest, new class implements RequestHandlerInterface {
63
            public function handle(ServerRequestInterface $request): ResponseInterface
64
            {
65
                return (new Factory())->createResponse(200);
66
            }
67
        });
68
69
    }
70
71
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
72
    {
73
        return $this->next($handler)->handle($request);
74
    }
75
76
    private function next(RequestHandlerInterface $defaultHandler): RequestHandlerInterface
77
    {
78
        return new class ($this->currentMiddlewares, $defaultHandler) implements RequestHandlerInterface {
79
            private RequestHandlerInterface $handler;
80
            private array $pipeline;
81
82
            public function __construct(array $pipeline, RequestHandlerInterface $handler)
83
            {
84
                $this->handler = $handler;
85
                $this->pipeline = $pipeline;
86
            }
87
88
            public function handle(ServerRequestInterface $request): ResponseInterface
89
            {
90
                if (!$middleware = array_shift($this->pipeline)) {
91
                    return $this->handler->handle($request);
92
                }
93
94
                $next = clone $this;
95
                $this->pipeline = [];
96
97
                return $middleware->process($request, $next);
98
            }
99
        };
100
    }
101
    
102
}
103