Completed
Push — json-pretty ( 698f4c )
by Carsten
06:07
created

JsonResponseFormatter   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 56%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 9
c 1
b 0
f 1
lcom 1
cbo 5
dl 0
loc 70
ccs 14
cts 25
cp 0.56
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 8 2
A formatJson() 0 11 3
A formatJsonp() 0 10 4
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\helpers\Json;
13
14
/**
15
 * JsonResponseFormatter formats the given data into a JSON or JSONP response content.
16
 *
17
 * It is used by [[Response]] to format response data.
18
 *
19
 * To configure properties like [[encodeOptions]] or [[prettyPrint]], you can configure the `response`
20
 * application component like the following:
21
 *
22
 * ```php
23
 * 'response' => [
24
 *     // ...
25
 *     'formatters' => [
26
 *         \yii\web\Response::FORMAT_JSON => [
27
 *              'class' => 'yii\web\JsonResponseFormatter',
28
 *              'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode
29
 *              // ...
30
 *         ],
31
 *     ],
32
 * ],
33
 * ```
34
 *
35
 * @author Qiang Xue <[email protected]>
36
 * @since 2.0
37
 */
38
class JsonResponseFormatter extends Component implements ResponseFormatterInterface
39
{
40
    /**
41
     * @var boolean whether to use JSONP response format. When this is true, the [[Response::data|response data]]
42
     * must be an array consisting of `data` and `callback` members. The latter should be a JavaScript
43
     * function name while the former will be passed to this function as a parameter.
44
     */
45
    public $useJsonp = false;
46
    /**
47
     * @var integer the encoding options passed to [[Json::encode()]]. For more details please refer to
48
     * <http://www.php.net/manual/en/function.json-encode.php>.
49
     * Default is `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`.
50
     * This property has no effect, when [[useJsonp]] is `true`.
51
     * @since 2.0.7
52
     */
53
    public $encodeOptions = 320;
54
    /**
55
     * @var bool whether to format the output in a readable "pretty" format. This can be useful for debugging purpose.
56
     * If this is true, `JSON_PRETTY_PRINT` will be added to [[encodeOptions]].
57
     * Defaults to `false`.
58
     * This property has no effect, when [[useJsonp]] is `true`.
59
     * @since 2.0.7
60
     */
61
    public $prettyPrint = false;
62
63
64
    /**
65
     * Formats the specified response.
66
     * @param Response $response the response to be formatted.
67
     */
68 19
    public function format($response)
69
    {
70 19
        if ($this->useJsonp) {
71
            $this->formatJsonp($response);
72
        } else {
73 19
            $this->formatJson($response);
74
        }
75 19
    }
76
77
    /**
78
     * Formats response data in JSON format.
79
     * @param Response $response
80
     */
81 19
    protected function formatJson($response)
82
    {
83 19
        $response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8');
84 19
        if ($response->data !== null) {
85 18
            $options = $this->encodeOptions;
86 18
            if ($this->prettyPrint) {
87 5
                $options |= JSON_PRETTY_PRINT;
88 5
            }
89 18
            $response->content = Json::encode($response->data, $options);
90 18
        }
91 19
    }
92
93
    /**
94
     * Formats response data in JSONP format.
95
     * @param Response $response
96
     */
97
    protected function formatJsonp($response)
98
    {
99
        $response->getHeaders()->set('Content-Type', 'application/javascript; charset=UTF-8');
100
        if (is_array($response->data) && isset($response->data['data'], $response->data['callback'])) {
101
            $response->content = sprintf('%s(%s);', $response->data['callback'], Json::htmlEncode($response->data['data']));
102
        } elseif ($response->data !== null) {
103
            $response->content = '';
104
            Yii::warning("The 'jsonp' response requires that the data be an array consisting of both 'data' and 'callback' elements.", __METHOD__);
105
        }
106
    }
107
}
108