JsonView   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 13
dl 0
loc 52
rs 10
c 0
b 0
f 0

4 Methods

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