Completed
Pull Request — master (#283)
by Phil
22:36
created

ApplicationStrategy::getExceptionHandler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace League\Route\Strategy;
6
7
use League\Route\Http\Exception\{MethodNotAllowedException, NotFoundException};
8
use League\Route\Route;
9
use League\Route\{ContainerAwareInterface, ContainerAwareTrait};
10
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
11
use Psr\Http\Server\{MiddlewareInterface, RequestHandlerInterface};
12
use Throwable;
13
14
class ApplicationStrategy extends AbstractStrategy implements ContainerAwareInterface
15
{
16
    use ContainerAwareTrait;
17
18
    public function getMethodNotAllowedDecorator(MethodNotAllowedException $exception): MiddlewareInterface
19 15
    {
20
        return $this->throwThrowableMiddleware($exception);
21 15
    }
22
23 15
    public function getNotFoundDecorator(NotFoundException $exception): MiddlewareInterface
24 12
    {
25
        return $this->throwThrowableMiddleware($exception);
26 12
    }
27
28
    public function getThrowableHandler(): MiddlewareInterface
29
    {
30
        return new class implements MiddlewareInterface
31
        {
32 18
            public function process(
33
                ServerRequestInterface $request,
34 18
                RequestHandlerInterface $requestHandler
35
            ): ResponseInterface {
36
                try {
37
                    return $requestHandler->handle($request);
38
                } catch (Throwable $e) {
39
                    throw $e;
40 6
                }
41
            }
42 6
        };
43
    }
44
45
    public function invokeRouteCallable(Route $route, ServerRequestInterface $request): ResponseInterface
46
    {
47
        $controller = $route->getCallable($this->getContainer());
48
        $response = $controller($request, $route->getVars());
49
        return $this->decorateResponse($response);
50
    }
51
52
    protected function throwThrowableMiddleware(Throwable $error): MiddlewareInterface
53
    {
54
        return new class ($error) implements MiddlewareInterface
55
        {
56
            protected $error;
57
58 24
            public function __construct(Throwable $error)
59
            {
60 24
                $this->error = $error;
61 24
            }
62
63 24
            public function process(
64
                ServerRequestInterface $request,
65
                RequestHandlerInterface $requestHandler
66
            ): ResponseInterface {
67 24
                throw $this->error;
68
            }
69
        };
70
    }
71
}
72