Completed
Push — master ( 7dba56...6875ae )
by Oscar
10:21
created

FastRoute   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 14
Bugs 1 Features 3
Metric Value
wmc 7
c 14
b 1
f 3
lcom 1
cbo 4
dl 0
loc 65
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A router() 0 6 1
A __invoke() 0 20 4
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr7Middlewares\Utils;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use FastRoute\Dispatcher;
9
10
class FastRoute
11
{
12
    use Utils\CallableTrait;
13
14
    /**
15
     * @var Dispatcher|null FastRoute dispatcher
16
     */
17
    private $router;
18
19
    /**
20
     * Constructor. Set Dispatcher instance.
21
     *
22
     * @param Dispatcher|null $router
23
     */
24
    public function __construct(Dispatcher $router = null)
25
    {
26
        if ($router !== null) {
27
            $this->router($router);
28
        }
29
    }
30
31
    /**
32
     * Extra arguments passed to the controller.
33
     *
34
     * @param Dispatcher $router
35
     *
36
     * @return self
37
     */
38
    public function router(Dispatcher $router)
39
    {
40
        $this->router = $router;
41
42
        return $this;
43
    }
44
45
    /**
46
     * Execute the middleware.
47
     *
48
     * @param ServerRequestInterface $request
49
     * @param ResponseInterface      $response
50
     * @param callable               $next
51
     *
52
     * @return ResponseInterface
53
     */
54
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
55
    {
56
        $route = $this->router->dispatch($request->getMethod(), $request->getUri()->getPath());
57
58
        if ($route[0] === Dispatcher::NOT_FOUND) {
59
            return $response->withStatus(404);
60
        }
61
62
        if ($route[0] === Dispatcher::METHOD_NOT_ALLOWED) {
63
            return $response->withStatus(405);
64
        }
65
66
        foreach ($route[2] as $name => $value) {
67
            $request = $request->withAttribute($name, $value);
68
        }
69
70
        $response = $this->executeCallable($route[1], $request, $response);
71
72
        return $next($request, $response);
73
    }
74
}
75