JsonResponse   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 62
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A setData() 0 12 2
A setContent() 0 9 2
A computeContent() 0 7 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