InvokerRouterMiddleware   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 1
cbo 6
dl 0
loc 56
ccs 26
cts 26
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A createDispatcherFromRouteArray() 0 11 2
A __construct() 0 7 1
A getRoute() 0 15 3
A process() 0 11 2
1
<?php
2
3
namespace IdNet\InvokerRouterMiddleware;
4
5
use FastRoute\Dispatcher;
6
use FastRoute\RouteCollector;
7
use function FastRoute\simpleDispatcher;
8
use IdNet\InvokerRouterMiddleware\Exception\MethodNotAllowedException;
9
use IdNet\InvokerRouterMiddleware\Exception\NotFoundException;
10
use Interop\Http\Server\MiddlewareInterface;
11
use Interop\Http\Server\RequestHandlerInterface;
12
use Invoker\InvokerInterface;
13
use Psr\Http\Message\ResponseInterface;
14
use Psr\Http\Message\ServerRequestInterface;
15
16
class InvokerRouterMiddleware implements MiddlewareInterface
17
{
18 1
    public static function createDispatcherFromRouteArray($routes)
19
    {
20 1
        return simpleDispatcher(
21 1
            function (RouteCollector $collector) use ($routes) {
22 1
                foreach ($routes as $route) {
23 1
                    call_user_func_array([$collector, 'addRoute'], $route);
24
                }
25 1
                return $collector;
26 1
            }
27
        );
28
    }
29
30
    /** @var \FastRoute\Dispatcher */
31
    protected $dispatcher;
32
33
    /** @var \Invoker\InvokerInterface */
34
    protected $invoker;
35
36 3
    public function __construct(
37
        Dispatcher $dispatcher,
38
        InvokerInterface $invoker
39
    ) {
40 3
        $this->dispatcher = $dispatcher;
41 3
        $this->invoker = $invoker;
42 3
    }
43
44 3
    public function process(
45
        ServerRequestInterface $request,
46
        RequestHandlerInterface $handler
47
    ): ResponseInterface {
48 3
        list($action, $vars) = $this->getRoute($request);
49
50 1
        foreach ($vars as $key => $value) {
51 1
            $request = $request->withAttribute($key, $value);
52
        }
53 1
        return $this->invoker->call($action, ['request' => $request]);
54
    }
55
56 3
    private function getRoute(ServerRequestInterface $request)
57
    {
58 3
        $route = $this->dispatcher->dispatch(
59 3
            $request->getMethod(),
60 3
            $request->getUri()->getPath()
61
        );
62 3
        $status = array_shift($route);
63 3
        if ($status === Dispatcher::FOUND) {
64 1
            return $route;
65
        }
66 2
        if ($status === Dispatcher::METHOD_NOT_ALLOWED) {
67 1
            throw new MethodNotAllowedException($request, $route[0]);
68
        }
69 1
        throw new NotFoundException($request);
70
    }
71
}
72