RoutingHandler   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 94.44%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 5
dl 0
loc 50
c 0
b 0
f 0
ccs 17
cts 18
cp 0.9444
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A handle() 0 10 2
A failure() 0 10 3
A success() 0 8 2
1
<?php
2
declare(strict_types=1);
3
4
namespace N1215\Http\Router\Handler;
5
6
use LogicException;
7
use N1215\Http\Router\Exception\RoutingException;
8
use N1215\Http\Router\RouterInterface;
9
use N1215\Http\Router\RoutingResultInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Http\Message\ServerRequestInterface;
12
13
final class RoutingHandler implements RoutingHandlerInterface
14
{
15
    /** @var RouterInterface */
16
    private $router;
17
18
    /** @var RoutingErrorResponderInterface[] */
19
    private $errorResponders;
20
21 3
    public function __construct(
22
        RouterInterface $router,
23
        RoutingErrorResponderInterface ...$errorResponders
24
    ) {
25 3
        $this->router = $router;
26 3
        $this->errorResponders = $errorResponders;
27 3
    }
28
29
    /**
30
     * @inheritDoc
31
     */
32 3
    public function handle(ServerRequestInterface $request): ResponseInterface
33
    {
34
        try {
35 3
            $result = $this->router->match($request);
36 2
        } catch (RoutingException $exception) {
37 2
            return $this->failure($exception, $request);
38
        }
39
40 1
        return $this->success($result, $request);
41
    }
42
43 2
    private function failure(RoutingException $exception, ServerRequestInterface $request): ResponseInterface
44
    {
45 2
        foreach ($this->errorResponders as $errorResponder) {
46 2
            if ($errorResponder->supports($exception)) {
47 2
                return $errorResponder->respond($exception, $request);
48
            }
49
        }
50
51
        throw new LogicException('a not supported routing exception `' . get_class($exception) . '` was thrown.');
52
    }
53
54 1
    private function success(RoutingResultInterface $result, ServerRequestInterface $request): ResponseInterface
55
    {
56 1
        foreach ($result->getParams() as $name => $value) {
57 1
            $request = $request->withAttribute($name, $value);
58
        }
59
60 1
        return $result->getHandler()->handle($request);
61
    }
62
}
63