JsonResponse::setData()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
1
<?php
2
/*
3
 * This file is part of the Borobudur-Http package.
4
 *
5
 * (c) Hexacodelabs <http://hexacodelabs.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Borobudur\Http\Response;
12
13
use Borobudur\Http\Exception\RuntimeException;
14
use Borobudur\Http\Header\Content\ContentTypeHeader;
15
use Borobudur\Http\Response;
16
17
/**
18
 * @author      Iqbal Maulana <[email protected]>
19
 * @created     8/2/15
20
 */
21
class JsonResponse extends Response
22
{
23
    /**
24
     * Constructor.
25
     *
26
     * @param array|null $data
27
     * @param int        $status
28
     * @param array      $headers
29
     */
30
    public function __construct(array $data = null, $status = 200, array $headers = array())
31
    {
32
        parent::__construct('', $status, $headers);
33
34
        if (null !== $data) {
35
            $this->setData($data);
36
        }
37
    }
38
39
    /**
40
     * Set and encode array data to json string and set to content.
41
     *
42
     * @param array $data
43
     *
44
     * @return $this
45
     */
46
    public function setData(array $data)
47
    {
48
        try {
49
            $data = json_encode($data);
50
        } catch(RuntimeException $exception) {
51
            throw new $exception;
52
        }
53
54
        $this->setContent($data);
55
56
        return $this;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function setContent($content)
63
    {
64
        // If array content detected then send to setData.
65
        if (is_array($content)) {
66
            return $this->setData($content);
67
        }
68
69
        return parent::setContent($content);
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    protected function computeContent()
76
    {
77
        // Force application/json header.
78
        $this->headers->set(new ContentTypeHeader('application/json'), true);
79
80
        return parent::computeContent();
81
    }
82
}
83