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

JsonStrategy   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 6
c 2
b 0
f 1
lcom 0
cbo 4
dl 0
loc 32
ccs 16
cts 16
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B dispatch() 0 26 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