JsonResponse.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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. namespace Symfony\Component\HttpFoundation;
  11. /**
  12. * Response represents an HTTP response in JSON format.
  13. *
  14. * Note that this class does not force the returned JSON content to be an
  15. * object. It is however recommended that you do return an object as it
  16. * protects yourself against XSSI and JSON-JavaScript Hijacking.
  17. *
  18. * @see https://www.owasp.org/index.php/OWASP_AJAX_Security_Guidelines#Always_return_JSON_with_an_Object_on_the_outside
  19. *
  20. * @author Igor Wiedler <igor@wiedler.ch>
  21. */
  22. class JsonResponse extends Response
  23. {
  24. protected $data;
  25. protected $callback;
  26. // Encode <, >, ', &, and " characters in the JSON, making it also safe to be embedded into HTML.
  27. // 15 === JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
  28. const DEFAULT_ENCODING_OPTIONS = 15;
  29. protected $encodingOptions = self::DEFAULT_ENCODING_OPTIONS;
  30. /**
  31. * @param mixed $data The response data
  32. * @param int $status The response status code
  33. * @param array $headers An array of response headers
  34. * @param bool $json If the data is already a JSON string
  35. */
  36. public function __construct($data = null, $status = 200, $headers = array(), $json = false)
  37. {
  38. parent::__construct('', $status, $headers);
  39. if (null === $data) {
  40. $data = new \ArrayObject();
  41. }
  42. $json ? $this->setJson($data) : $this->setData($data);
  43. }
  44. /**
  45. * Factory method for chainability.
  46. *
  47. * Example:
  48. *
  49. * return JsonResponse::create($data, 200)
  50. * ->setSharedMaxAge(300);
  51. *
  52. * @param mixed $data The json response data
  53. * @param int $status The response status code
  54. * @param array $headers An array of response headers
  55. *
  56. * @return static
  57. */
  58. public static function create($data = null, $status = 200, $headers = array())
  59. {
  60. return new static($data, $status, $headers);
  61. }
  62. /**
  63. * Make easier the creation of JsonResponse from raw json.
  64. */
  65. public static function fromJsonString($data = null, $status = 200, $headers = array())
  66. {
  67. return new static($data, $status, $headers, true);
  68. }
  69. /**
  70. * Sets the JSONP callback.
  71. *
  72. * @param string|null $callback The JSONP callback or null to use none
  73. *
  74. * @return $this
  75. *
  76. * @throws \InvalidArgumentException When the callback name is not valid
  77. */
  78. public function setCallback($callback = null)
  79. {
  80. if (null !== $callback) {
  81. // partially taken from http://www.geekality.net/2011/08/03/valid-javascript-identifier/
  82. // partially taken from https://github.com/willdurand/JsonpCallbackValidator
  83. // JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details.
  84. // (c) William Durand <william.durand1@gmail.com>
  85. $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u';
  86. $reserved = array(
  87. 'break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while',
  88. 'debugger', 'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 'extends', 'super', 'const', 'export',
  89. 'import', 'implements', 'let', 'private', 'public', 'yield', 'interface', 'package', 'protected', 'static', 'null', 'true', 'false',
  90. );
  91. $parts = explode('.', $callback);
  92. foreach ($parts as $part) {
  93. if (!preg_match($pattern, $part) || in_array($part, $reserved, true)) {
  94. throw new \InvalidArgumentException('The callback name is not valid.');
  95. }
  96. }
  97. }
  98. $this->callback = $callback;
  99. return $this->update();
  100. }
  101. /**
  102. * Sets a raw string containing a JSON document to be sent.
  103. *
  104. * @param string $json
  105. *
  106. * @return $this
  107. *
  108. * @throws \InvalidArgumentException
  109. */
  110. public function setJson($json)
  111. {
  112. $this->data = $json;
  113. return $this->update();
  114. }
  115. /**
  116. * Sets the data to be sent as JSON.
  117. *
  118. * @param mixed $data
  119. *
  120. * @return $this
  121. *
  122. * @throws \InvalidArgumentException
  123. */
  124. public function setData($data = array())
  125. {
  126. if (defined('HHVM_VERSION')) {
  127. // HHVM does not trigger any warnings and let exceptions
  128. // thrown from a JsonSerializable object pass through.
  129. // If only PHP did the same...
  130. $data = json_encode($data, $this->encodingOptions);
  131. } else {
  132. try {
  133. // PHP 5.4 and up wrap exceptions thrown by JsonSerializable
  134. // objects in a new exception that needs to be removed.
  135. // Fortunately, PHP 5.5 and up do not trigger any warning anymore.
  136. $data = json_encode($data, $this->encodingOptions);
  137. } catch (\Exception $e) {
  138. if ('Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
  139. throw $e->getPrevious() ?: $e;
  140. }
  141. throw $e;
  142. }
  143. }
  144. if (JSON_ERROR_NONE !== json_last_error()) {
  145. throw new \InvalidArgumentException(json_last_error_msg());
  146. }
  147. return $this->setJson($data);
  148. }
  149. /**
  150. * Returns options used while encoding data to JSON.
  151. *
  152. * @return int
  153. */
  154. public function getEncodingOptions()
  155. {
  156. return $this->encodingOptions;
  157. }
  158. /**
  159. * Sets options used while encoding data to JSON.
  160. *
  161. * @param int $encodingOptions
  162. *
  163. * @return $this
  164. */
  165. public function setEncodingOptions($encodingOptions)
  166. {
  167. $this->encodingOptions = (int) $encodingOptions;
  168. return $this->setData(json_decode($this->data));
  169. }
  170. /**
  171. * Updates the content and headers according to the JSON data and callback.
  172. *
  173. * @return $this
  174. */
  175. protected function update()
  176. {
  177. if (null !== $this->callback) {
  178. // Not using application/javascript for compatibility reasons with older browsers.
  179. $this->headers->set('Content-Type', 'text/javascript');
  180. return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data));
  181. }
  182. // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
  183. // in order to not overwrite a custom definition.
  184. if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) {
  185. $this->headers->set('Content-Type', 'application/json');
  186. }
  187. return $this->setContent($this->data);
  188. }
  189. }