Completed
Pull Request — master (#115)
by Phil
02:17
created

JsonStrategy::getExecutionChain()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 41
ccs 0
cts 33
cp 0
rs 8.439
cc 5
eloc 25
nc 2
nop 2
crap 30
1
<?php
2
3
namespace League\Route\Strategy;
4
5
use Exception;
6
use League\Route\Http\Exception as HttpException;
7
use League\Route\Middleware\ExecutionChain;
8
use League\Route\Route;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use RuntimeException;
12
13
class JsonStrategy implements StrategyInterface
14
{
15
    /**
16
     * {@inheritdoc}
17
     */
18
    public function getExecutionChain(Route $route, array $vars)
19
    {
20
        $middleware = function (
21
            ServerRequestInterface $request, ResponseInterface $response, callable $next
22
        ) use (
23
            $route, $vars
24
        ) {
25
            try {
26
                $response = call_user_func_array($route->getCallable(), [$request, $response, $vars]);
27
28
                if (! $response instanceof ResponseInterface) {
29
                    throw new RuntimeException(
30
                        'Route callables must return an instance of (Psr\Http\Message\ResponseInterface)'
31
                    );
32
                }
33
34
                $response = $response->withAddedHeader('content-type', 'application/json');
35
                $response = $next($request, $response);
36
            } catch (HttpException $e) {
37
                $response = $e->buildJsonResponse($response);
38
            } catch (Exception $e) {
39
                $body = [
40
                    'code'    => 500,
41
                    'message' => $e->getMessage()
42
                ];
43
44
                $response->getBody()->write(json_encode($body));
45
                $response = $response->withStatus(500);
46
            }
47
48
            return $response;
49
        };
50
51
        $execChain = (new ExecutionChain)->middleware($middleware);
52
53
        foreach ($route->getMiddlewareStack() as $middleware) {
54
            $execChain->middleware($middleware);
55
        }
56
57
        return $execChain;
58
    }
59
}
60