RequestJsonStrategy::call()   A
last analyzed

Complexity

Conditions 4
Paths 9

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 19
ccs 11
cts 11
cp 1
rs 9.2
cc 4
eloc 11
nc 9
nop 1
crap 4
1
<?php
2
3
/**
4
 * Codeburner Framework.
5
 *
6
 * @author Alex Rohleder <[email protected]>
7
 * @copyright 2016 Alex Rohleder
8
 * @license http://opensource.org/licenses/MIT
9
 */
10
11
namespace Codeburner\Router\Strategies;
12
13
use Psr\Http\Message\ResponseInterface;
14
use Codeburner\Router\Exceptions\Http\HttpExceptionAbstract;
15
use Codeburner\Router\Route;
16
use RuntimeException;
17
18
/**
19
 * The action will receive one Psr\Http\Message\RequestInterface object and one array with parameters
20
 * from pattern, and the return will create a json response, with right headers.
21
 *
22
 * @author Alex Rohleder <[email protected]>
23
 */
24
25
class RequestJsonStrategy implements StrategyInterface
26
{
27
28
    use RequestAwareTrait;
29
30
    /**
31
     * @inheritdoc
32
     * @throws RuntimeException
33
     * @return ResponseInterface
34
     */
35
36 3
    public function call(Route $route)
37
    {
38
        try {
39 3
            $response = call_user_func($route->getAction(), $this->request, $route->getMergedParams());
40
41 2
            if (is_array($response)) {
42 1
                $this->response->getBody()->write(json_encode($response));
43 1
                $response = $this->response;
44 1
            }
45
46 2
            if ($response instanceof ResponseInterface) {
47 1
                return $response->withAddedHeader("content-type", "application/json");
48
            }
49 2
        } catch (HttpExceptionAbstract $e) {
50 1
            return $e->getJsonResponse($this->response);
51
        }
52
53 1
        throw new RuntimeException("Unable to determine a json response from action returned value.");
54
    }
55
56
}
57