Completed
Pull Request — master (#115)
by Phil
03:31
created

JsonStrategy   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 0 Features 1
Metric Value
wmc 5
c 5
b 0
f 1
lcom 0
cbo 3
dl 0
loc 50
ccs 24
cts 24
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B getExecutionChain() 0 44 5
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 9
        $middleware = function (
21
            ServerRequestInterface $request, ResponseInterface $response, callable $next
22
        ) use (
23 9
            $route, $vars
24
        ) {
25
            try {
26 9
                $return = call_user_func_array($route->getCallable(), [$request, $response, $vars]);
27
28 6
                if (! $return instanceof ResponseInterface) {
29 3
                    throw new RuntimeException(
30
                        'Route callables must return an instance of (Psr\Http\Message\ResponseInterface)'
31 3
                    );
32
                }
33
34 3
                $response = $return;
35 3
                $response = $next($request, $response);
36 9
            } catch (HttpException $e) {
37 3
                return $e->buildJsonResponse($response);
38 3
            } catch (Exception $e) {
39
                $body = [
40 3
                    'status_code'   => 500,
41 3
                    'reason_phrase' => $e->getMessage()
42 3
                ];
43
44 3
                $response->getBody()->write(json_encode($body));
45 3
                $response = $response->withStatus(500);
46
            }
47
48 6
            return $response->withAddedHeader('content-type', 'application/json');
49 9
        };
50
51 9
        $execChain = (new ExecutionChain)->middleware($middleware);
52
53
        // ensure middleware is executed in the order it was added
54 9
        $stack = array_reverse($route->getMiddlewareStack());
55
56 9
        foreach ($stack as $middleware) {
57 3
            $execChain->middleware($middleware);
58 9
        }
59
60 9
        return $execChain;
61
    }
62
}
63