You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.2KB

  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. namespace yii\web;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\helpers\Json;
  11. /**
  12. * JsonResponseFormatter formats the given data into a JSON or JSONP response content.
  13. *
  14. * It is used by [[Response]] to format response data.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @since 2.0
  18. */
  19. class JsonResponseFormatter extends Component implements ResponseFormatterInterface
  20. {
  21. /**
  22. * @var boolean whether to use JSONP response format. When this is true, the [[Response::data|response data]]
  23. * must be an array consisting of `data` and `callback` members. The latter should be a JavaScript
  24. * function name while the former will be passed to this function as a parameter.
  25. */
  26. public $useJsonp = false;
  27. /**
  28. * Formats the specified response.
  29. * @param Response $response the response to be formatted.
  30. */
  31. public function format($response)
  32. {
  33. if ($this->useJsonp) {
  34. $this->formatJsonp($response);
  35. } else {
  36. $this->formatJson($response);
  37. }
  38. }
  39. /**
  40. * Formats response data in JSON format.
  41. * @param Response $response
  42. */
  43. protected function formatJson($response)
  44. {
  45. $response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8');
  46. if ($response->data !== null) {
  47. $response->content = Json::encode($response->data);
  48. }
  49. }
  50. /**
  51. * Formats response data in JSONP format.
  52. * @param Response $response
  53. */
  54. protected function formatJsonp($response)
  55. {
  56. $response->getHeaders()->set('Content-Type', 'application/javascript; charset=UTF-8');
  57. if (is_array($response->data) && isset($response->data['data'], $response->data['callback'])) {
  58. $response->content = sprintf('%s(%s);', $response->data['callback'], Json::encode($response->data['data']));
  59. } elseif ($response->data !== null) {
  60. $response->content = '';
  61. Yii::warning("The 'jsonp' response requires that the data be an array consisting of both 'data' and 'callback' elements.", __METHOD__);
  62. }
  63. }
  64. }