|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- <?php
-
-
- namespace yii\web;
-
- use Yii;
- use yii\base\Component;
- use yii\helpers\Json;
-
-
- class JsonResponseFormatter extends Component implements ResponseFormatterInterface
- {
-
-
- public $useJsonp = false;
-
-
- public $encodeOptions = 320;
-
-
- public $prettyPrint = false;
-
-
-
-
- public function format($response)
- {
- if ($this->useJsonp) {
- $this->formatJsonp($response);
- } else {
- $this->formatJson($response);
- }
- }
-
-
-
- protected function formatJson($response)
- {
- $response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8');
- if ($response->data !== null) {
- $options = $this->encodeOptions;
- if ($this->prettyPrint) {
- $options |= JSON_PRETTY_PRINT;
- }
- $response->content = Json::encode($response->data, $options);
- }
- }
-
-
-
- protected function formatJsonp($response)
- {
- $response->getHeaders()->set('Content-Type', 'application/javascript; charset=UTF-8');
- if (is_array($response->data) && isset($response->data['data'], $response->data['callback'])) {
- $response->content = sprintf('%s(%s);', $response->data['callback'], Json::htmlEncode($response->data['data']));
- } elseif ($response->data !== null) {
- $response->content = '';
- Yii::warning("The 'jsonp' response requires that the data be an array consisting of both 'data' and 'callback' elements.", __METHOD__);
- }
- }
- }
|