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

RequestResponseJsonStrategy   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 0%

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B dispatch() 0 32 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 Psr\Http\Message\ServerRequestInterface;
10
use RuntimeException;
11
12
class RequestResponseJsonStrategy extends AbstractStrategy implements StrategyInterface
13
{
14
    /**
15
     * {@inheritdoc}
16
     */
17
    public function dispatch(callable $controller, array $vars, Route $route = null)
18
    {
19
        $middleware = function (
20
            ServerRequestInterface $request, ResponseInterface $response, callable $next
21
        ) use (
22
            $controller, $vars
23
        ) {
24
            try {
25
                $result = call_user_func_array($controller, [$request, $response, $vars]);
26
27
                if (is_array($result) || $result instanceof ArrayObject) {
28
                    $body     = json_encode($result);
29
                    $response = $this->getResponse();
30
31
                    if ($response->getBody()->isWritable()) {
32
                        $response->getBody()->write($body);
33
                    }
34
                }
35
36
                if ($response instanceof ResponseInterface) {
37
                    $response = $response->withAddedHeader('content-type', 'application/json');
38
                    return $next($request, $response);
39
                }
40
            } catch (HttpException $e) {
41
                return $e->buildJsonResponse($this->getResponse());
42
            }
43
44
            throw new RuntimeException('Unable to build a json response from controller return value.');
45
        };
46
47
        return $route->getMiddlewareRunner()->run($middleware, $this->getRequest(), $this->getResponse());
0 ignored issues
show
Bug introduced by
It seems like $route is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
48
    }
49
}
50