Passed
Push — master ( 0fa97a...3e03bc )
by Felipe
02:17
created

RouterHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of coisa/http.
4
 *
5
 * (c) Felipe Sayão Lobato Abreu <[email protected]>
6
 *
7
 * This source file is subject to the license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace CoiSA\Http\Handler;
12
13
use CoiSA\Http\Middleware\PregMatchRequestTargetMiddleware;
14
use CoiSA\Http\Middleware\RequestMethodMiddleware;
15
use Psr\Http\Message\ResponseInterface;
16
use Psr\Http\Message\ServerRequestInterface;
17
use Psr\Http\Server\MiddlewareInterface;
18
use Psr\Http\Server\RequestHandlerInterface;
19
20
/**
21
 * Class RouterHandler
22
 *
23
 * @package CoiSA\Http\Handler
24
 */
25
final class RouterHandler implements RequestHandlerInterface
26
{
27
    /**
28
     * @var RequestHandlerInterface
29
     */
30
    private $notFoundHandler;
31
32
    /**
33
     * @var MiddlewareInterface[]
34
     */
35
    private $routes;
36
37
    /**
38
     * RouterHandler constructor.
39
     *
40
     * @param RequestHandlerInterface $notFoundHandler
41
     */
42
    public function __construct(RequestHandlerInterface $notFoundHandler)
43
    {
44
        $this->notFoundHandler = $notFoundHandler;
45
    }
46
47
    /**
48
     * @param string                  $method
49
     * @param string                  $regex
50
     * @param RequestHandlerInterface $requestHandler
51
     */
52
    public function addRoute(string $method, string $regex, RequestHandlerInterface $requestHandler): void
53
    {
54
        $middleware     = new RequestMethodMiddleware($method, $requestHandler);
55
        $this->routes[] = new PregMatchRequestTargetMiddleware(
56
            $regex,
57
            new MiddlewareHandler($middleware, $this)
58
        );
59
        \reset($this->routes);
60
    }
61
62
    /**
63
     * @param ServerRequestInterface $request
64
     *
65
     * @return ResponseInterface
66
     */
67
    public function handle(ServerRequestInterface $request): ResponseInterface
68
    {
69
        $middleware = \current($this->routes);
70
71
        if (!$middleware) {
72
            \reset($this->routes);
73
74
            return $this->notFoundHandler->handle($request);
75
        }
76
77
        \next($this->routes);
78
79
        return $middleware->process($request, $this);
80
    }
81
}
82