-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathJsonView.php
More file actions
65 lines (56 loc) · 1.63 KB
/
JsonView.php
File metadata and controls
65 lines (56 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
declare(strict_types=1);
namespace Lit\Voltage;
use Psr\Http\Message\ResponseInterface;
/**
* A simple view class doing json_encode for payloads.
*/
class JsonView extends AbstractView
{
public const JSON_ROOT = self::class;
protected $jsonOption = 0;
/**
* {@inheritDoc}
*
* You may use renderJson which receive any type instead of this.
*
* @param array $data Payload. If JsonView::JSON_ROOT exist in payload, it will be used instead of whole payload.
* @return ResponseInterface
*/
public function render(array $data = []): ResponseInterface
{
$jsonData = array_key_exists(static::JSON_ROOT, $data) ? $data[static::JSON_ROOT] : $data;
/** @var string $jsonString */
$jsonString = json_encode($jsonData, $this->jsonOption);
assert(json_last_error() === JSON_ERROR_NONE);
$this->getEmptyBody()->write($jsonString);
return $this->response
->withHeader('Content-Type', 'application/json');
}
/**
* Render method that receives any type of payload.
*
* @param mixed $value The payload to be outputed.
* @return ResponseInterface
*/
public function renderJson($value): ResponseInterface
{
return $this->render([static::JSON_ROOT => $value]);
}
/**
* @return integer
*/
public function getJsonOption(): int
{
return $this->jsonOption;
}
/**
* @param integer $jsonOption The new json option.
* @return $this
*/
public function setJsonOption(int $jsonOption)
{
$this->jsonOption = $jsonOption;
return $this;
}
}