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.
 
 
 
 
 
 

236 lines
7.7 KiB

  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://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/AJAX_Security_Cheat_Sheet.md#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 = [], $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(['key' => 'value'])
  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 = [])
  59. {
  60. return new static($data, $status, $headers);
  61. }
  62. /**
  63. * Factory method for chainability.
  64. *
  65. * Example:
  66. *
  67. * return JsonResponse::fromJsonString('{"key": "value"}')
  68. * ->setSharedMaxAge(300);
  69. *
  70. * @param string|null $data The JSON response string
  71. * @param int $status The response status code
  72. * @param array $headers An array of response headers
  73. *
  74. * @return static
  75. */
  76. public static function fromJsonString($data = null, $status = 200, $headers = [])
  77. {
  78. return new static($data, $status, $headers, true);
  79. }
  80. /**
  81. * Sets the JSONP callback.
  82. *
  83. * @param string|null $callback The JSONP callback or null to use none
  84. *
  85. * @return $this
  86. *
  87. * @throws \InvalidArgumentException When the callback name is not valid
  88. */
  89. public function setCallback($callback = null)
  90. {
  91. if (null !== $callback) {
  92. // partially taken from https://geekality.net/2011/08/03/valid-javascript-identifier/
  93. // partially taken from https://github.com/willdurand/JsonpCallbackValidator
  94. // JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details.
  95. // (c) William Durand <william.durand1@gmail.com>
  96. $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u';
  97. $reserved = [
  98. 'break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while',
  99. 'debugger', 'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 'extends', 'super', 'const', 'export',
  100. 'import', 'implements', 'let', 'private', 'public', 'yield', 'interface', 'package', 'protected', 'static', 'null', 'true', 'false',
  101. ];
  102. $parts = explode('.', $callback);
  103. foreach ($parts as $part) {
  104. if (!preg_match($pattern, $part) || \in_array($part, $reserved, true)) {
  105. throw new \InvalidArgumentException('The callback name is not valid.');
  106. }
  107. }
  108. }
  109. $this->callback = $callback;
  110. return $this->update();
  111. }
  112. /**
  113. * Sets a raw string containing a JSON document to be sent.
  114. *
  115. * @param string $json
  116. *
  117. * @return $this
  118. *
  119. * @throws \InvalidArgumentException
  120. */
  121. public function setJson($json)
  122. {
  123. $this->data = $json;
  124. return $this->update();
  125. }
  126. /**
  127. * Sets the data to be sent as JSON.
  128. *
  129. * @param mixed $data
  130. *
  131. * @return $this
  132. *
  133. * @throws \InvalidArgumentException
  134. */
  135. public function setData($data = [])
  136. {
  137. if (\defined('HHVM_VERSION')) {
  138. // HHVM does not trigger any warnings and let exceptions
  139. // thrown from a JsonSerializable object pass through.
  140. // If only PHP did the same...
  141. $data = json_encode($data, $this->encodingOptions);
  142. } else {
  143. if (!interface_exists('JsonSerializable', false)) {
  144. set_error_handler(function () { return false; });
  145. try {
  146. $data = @json_encode($data, $this->encodingOptions);
  147. } finally {
  148. restore_error_handler();
  149. }
  150. } else {
  151. try {
  152. $data = json_encode($data, $this->encodingOptions);
  153. } catch (\Exception $e) {
  154. if ('Exception' === \get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
  155. throw $e->getPrevious() ?: $e;
  156. }
  157. throw $e;
  158. }
  159. if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $this->encodingOptions)) {
  160. return $this->setJson($data);
  161. }
  162. }
  163. }
  164. if (JSON_ERROR_NONE !== json_last_error()) {
  165. throw new \InvalidArgumentException(json_last_error_msg());
  166. }
  167. return $this->setJson($data);
  168. }
  169. /**
  170. * Returns options used while encoding data to JSON.
  171. *
  172. * @return int
  173. */
  174. public function getEncodingOptions()
  175. {
  176. return $this->encodingOptions;
  177. }
  178. /**
  179. * Sets options used while encoding data to JSON.
  180. *
  181. * @param int $encodingOptions
  182. *
  183. * @return $this
  184. */
  185. public function setEncodingOptions($encodingOptions)
  186. {
  187. $this->encodingOptions = (int) $encodingOptions;
  188. return $this->setData(json_decode($this->data));
  189. }
  190. /**
  191. * Updates the content and headers according to the JSON data and callback.
  192. *
  193. * @return $this
  194. */
  195. protected function update()
  196. {
  197. if (null !== $this->callback) {
  198. // Not using application/javascript for compatibility reasons with older browsers.
  199. $this->headers->set('Content-Type', 'text/javascript');
  200. return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data));
  201. }
  202. // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
  203. // in order to not overwrite a custom definition.
  204. if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) {
  205. $this->headers->set('Content-Type', 'application/json');
  206. }
  207. return $this->setContent($this->data);
  208. }
  209. }