|
1
|
|
|
<?php |
|
2
|
|
|
namespace Core\Renderers; |
|
3
|
|
|
|
|
4
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
5
|
|
|
use Slim\Http\Body; |
|
6
|
|
|
|
|
7
|
|
|
class JsonApiRenderer |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* Bitmask consisting of <b>JSON_HEX_QUOT</b>, |
|
11
|
|
|
* <b>JSON_HEX_TAG</b>, |
|
12
|
|
|
* <b>JSON_HEX_AMP</b>, |
|
13
|
|
|
* <b>JSON_HEX_APOS</b>, |
|
14
|
|
|
* <b>JSON_NUMERIC_CHECK</b>, |
|
15
|
|
|
* <b>JSON_PRETTY_PRINT</b>, |
|
16
|
|
|
* <b>JSON_UNESCAPED_SLASHES</b>, |
|
17
|
|
|
* <b>JSON_FORCE_OBJECT</b>, |
|
18
|
|
|
* <b>JSON_UNESCAPED_UNICODE</b>. |
|
19
|
|
|
* The behaviour of these constants is described on |
|
20
|
|
|
* the JSON constants page. |
|
21
|
|
|
* @var int |
|
22
|
|
|
*/ |
|
23
|
|
|
/** |
|
24
|
|
|
* Output rendered template |
|
25
|
|
|
* |
|
26
|
|
|
* @param ResponseInterface $response |
|
27
|
|
|
* @param array $data Associative array of data to be returned |
|
28
|
|
|
* @param int $status HTTP status code |
|
29
|
|
|
* @param array $addHeaders Associative array of header to be added |
|
30
|
|
|
* @return ResponseInterface |
|
31
|
|
|
*/ |
|
32
|
|
|
public function render(ResponseInterface $response, array $data = [], $status = 200, $addHeaders = []) |
|
33
|
|
|
{ |
|
34
|
|
|
$status = intval($status); |
|
35
|
|
|
$output = [ |
|
36
|
|
|
'meta' => ['error' => true, 'status' => $status], |
|
37
|
|
|
'data' => $data, |
|
38
|
|
|
]; |
|
39
|
|
|
$output['meta']['error'] = ($status < 400) ? false : true; |
|
40
|
|
|
$json = json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); |
|
41
|
|
|
// Ensure that the json encoding passed successfully |
|
42
|
|
|
if ($json === false) { |
|
|
|
|
|
|
43
|
|
|
throw new \RuntimeException(json_last_error_msg(), json_last_error()); |
|
44
|
|
|
} |
|
45
|
|
|
$body = new Body(fopen('php://temp', 'r+')); |
|
|
|
|
|
|
46
|
|
|
$body->write($json); |
|
47
|
|
|
$newResponse = $response->withBody($body); |
|
48
|
|
|
$newResponse = $newResponse->withStatus($status) |
|
49
|
|
|
->withHeader('Content-Type', 'application/json;charset=utf-8'); |
|
50
|
|
|
if (count($addHeaders)) { |
|
51
|
|
|
foreach ($addHeaders as $headerKey => $headerValue) { |
|
52
|
|
|
if (strtolower($headerKey) != 'content-type') { |
|
53
|
|
|
$newResponse->withHeader($headerKey, $headerValue); |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
return $newResponse; |
|
58
|
|
|
} |
|
59
|
|
|
} |