Completed
Push — master ( b9d832...421ea6 )
by Phil
06:19 queued 04:14
created

JsonStrategy::dispatch()   B

Complexity

Conditions 6
Paths 15

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 6

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 26
ccs 16
cts 16
cp 1
rs 8.439
cc 6
eloc 15
nc 15
nop 3
crap 6
1
<?php
2
3
namespace League\Route\Strategy;
4
5
use ArrayObject;
6
use League\Route\Http\Exception as HttpException;
7
use League\Route\Route;
8
use Psr\Http\Message\ResponseInterface;
9
use RuntimeException;
10
11
class JsonStrategy extends AbstractStrategy implements StrategyInterface
12
{
13
    /**
14
     * {@inheritdoc}
15
     */
16 9
    public function dispatch(callable $controller, array $vars, Route $route = null)
17
    {
18
        try {
19 9
            $response = call_user_func_array($controller, [
20 9
                $this->getRequest(),
21
                $vars
22 9
            ]);
23
24 6
            if (is_array($response) || $response instanceof ArrayObject) {
25 3
                $body     = json_encode($response);
26 3
                $response = $this->getResponse();
27
28 3
                if ($response->getBody()->isWritable()) {
29 3
                    $response->getBody()->write($body);
30 3
                }
31 3
            }
32
33 6
            if ($response instanceof ResponseInterface) {
34 3
                return $response->withAddedHeader('content-type', 'application/json');
35
            }
36 6
        } catch (HttpException $e) {
37 3
            return $e->buildJsonResponse($this->getResponse());
38
        }
39
40 3
        throw new RuntimeException('Unable to build a json response from controller return value.');
41
    }
42
}
43