Passed
Push — master ( a071d4...32677b )
by Felipe
02:03
created

RoutingMiddleware::process()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 13
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 2
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\Middleware;
12
13
use CoiSA\Http\RouterInterface;
14
use Psr\Http\Message\ResponseInterface;
15
use Psr\Http\Message\ServerRequestInterface;
16
use Psr\Http\Server\MiddlewareInterface;
17
use Psr\Http\Server\RequestHandlerInterface;
18
19
/**
20
 * Class RoutingMiddleware
21
 *
22
 * @package CoiSA\Http\Middleware
23
 */
24
final class RoutingMiddleware implements MiddlewareInterface
25
{
26
    /**
27
     * @var RouterInterface
28
     */
29
    private $router;
30
31
    /**
32
     * RoutingMiddleware constructor.
33
     *
34
     * @param RouterInterface $router
35
     */
36
    public function __construct(RouterInterface $router)
37
    {
38
        $this->router = $router;
39
    }
40
41
    /**
42
     * @param ServerRequestInterface $request
43
     * @param RequestHandlerInterface $handler
44
     *
45
     * @return ResponseInterface
46
     */
47
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
48
    {
49
        $routeMatch = $this->router->match($request);
50
51
        if ($routeMatch->isSuccess()) {
52
            foreach ($routeMatch->getVariables() as $name => $value) {
53
                $request = $request->withAttribute($name, $value);
54
            }
55
56
            return $routeMatch->getHandler()->handle($request);
57
        }
58
59
        return $handler->handle($request);
60
    }
61
}
62