Passed
Branch master (7c3f6c)
by Javi
02:38
created

Router   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 3
dl 0
loc 59
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A attribute() 0 6 1
A process() 0 7 1
1
<?php
2
3
namespace itsjavi\Flatdown\Middlewares;
4
5
use FastRoute\Dispatcher as FastRouteDispatcher;
6
use Interop\Http\ServerMiddleware\DelegateInterface;
7
use Interop\Http\ServerMiddleware\MiddlewareInterface;
8
use itsjavi\Flatdown\Route\RouteCollector;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
12
class Router implements MiddlewareInterface
13
{
14
    /**
15
     * @var RouteCollector
16
     */
17
    private $router;
18
19
    /**
20
     * @var FastRouteDispatcher FastRoute dispatcher
21
     */
22
    private $dispatcher;
23
24
    /**
25
     * @var string Attribute name for handler reference
26
     */
27
    private $attribute = 'request-handler';
28
29
    /**
30
     * Set the Dispatcher instance.
31
     *
32
     * @param RouteCollector $router
33
     * @param FastRouteDispatcher $dispatcher
34
     */
35
    public function __construct(RouteCollector $router, FastRouteDispatcher $dispatcher = null)
36
    {
37
        $this->router     = $router;
38
        $this->dispatcher = $dispatcher;
39
    }
40
41
    /**
42
     * Set the attribute name to store handler reference.
43
     *
44
     * @param string $attribute
45
     *
46
     * @return self
47
     */
48
    public function attribute($attribute)
49
    {
50
        $this->attribute = $attribute;
51
52
        return $this;
53
    }
54
55
    /**
56
     * Process a server request and return a response.
57
     *
58
     * @param ServerRequestInterface $request
59
     * @param DelegateInterface $delegate
60
     *
61
     * @return ResponseInterface
62
     */
63
    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
64
    {
65
        $handler = $this->router->dispatch($request, $this->dispatcher);
66
        $request = $request->withAttribute($this->attribute, $handler);
67
68
        return $delegate->process($request);
69
    }
70
}
71