JsonResponse.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. protected $encodingOptions = 15;
  29. /**
  30. * @param mixed $data The response data
  31. * @param int $status The response status code
  32. * @param array $headers An array of response headers
  33. */
  34. public function __construct($data = null, $status = 200, $headers = array())
  35. {
  36. parent::__construct('', $status, $headers);
  37. if (null === $data) {
  38. $data = new \ArrayObject();
  39. }
  40. $this->setData($data);
  41. }
  42. /**
  43. * Factory method for chainability.
  44. *
  45. * Example:
  46. *
  47. * return JsonResponse::create($data, 200)
  48. * ->setSharedMaxAge(300);
  49. *
  50. * @param mixed $data The json response data
  51. * @param int $status The response status code
  52. * @param array $headers An array of response headers
  53. *
  54. * @return static
  55. */
  56. public static function create($data = null, $status = 200, $headers = array())
  57. {
  58. return new static($data, $status, $headers);
  59. }
  60. /**
  61. * Sets the JSONP callback.
  62. *
  63. * @param string|null $callback The JSONP callback or null to use none
  64. *
  65. * @return $this
  66. *
  67. * @throws \InvalidArgumentException When the callback name is not valid
  68. */
  69. public function setCallback($callback = null)
  70. {
  71. if (null !== $callback) {
  72. // partially token from http://www.geekality.net/2011/08/03/valid-javascript-identifier/
  73. // partially token from https://github.com/willdurand/JsonpCallbackValidator
  74. // JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details.
  75. // (c) William Durand <william.durand1@gmail.com>
  76. $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u';
  77. $reserved = array(
  78. 'break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while',
  79. 'debugger', 'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 'extends', 'super', 'const', 'export',
  80. 'import', 'implements', 'let', 'private', 'public', 'yield', 'interface', 'package', 'protected', 'static', 'null', 'true', 'false',
  81. );
  82. $parts = explode('.', $callback);
  83. foreach ($parts as $part) {
  84. if (!preg_match($pattern, $part) || \in_array($part, $reserved, true)) {
  85. throw new \InvalidArgumentException('The callback name is not valid.');
  86. }
  87. }
  88. }
  89. $this->callback = $callback;
  90. return $this->update();
  91. }
  92. /**
  93. * Sets the data to be sent as JSON.
  94. *
  95. * @param mixed $data
  96. *
  97. * @return $this
  98. *
  99. * @throws \InvalidArgumentException
  100. */
  101. public function setData($data = array())
  102. {
  103. if (\defined('HHVM_VERSION')) {
  104. // HHVM does not trigger any warnings and let exceptions
  105. // thrown from a JsonSerializable object pass through.
  106. // If only PHP did the same...
  107. $data = json_encode($data, $this->encodingOptions);
  108. } else {
  109. try {
  110. if (!interface_exists('JsonSerializable', false)) {
  111. // PHP 5.3 triggers annoying warnings for some
  112. // types that can't be serialized as JSON (INF, resources, etc.)
  113. // but doesn't provide the JsonSerializable interface.
  114. set_error_handler(function () { return false; });
  115. $data = @json_encode($data, $this->encodingOptions);
  116. restore_error_handler();
  117. } elseif (\PHP_VERSION_ID < 50500) {
  118. // PHP 5.4 and up wrap exceptions thrown by JsonSerializable
  119. // objects in a new exception that needs to be removed.
  120. // Fortunately, PHP 5.5 and up do not trigger any warning anymore.
  121. // Clear json_last_error()
  122. json_encode(null);
  123. $errorHandler = set_error_handler('var_dump');
  124. restore_error_handler();
  125. set_error_handler(function () use ($errorHandler) {
  126. if (JSON_ERROR_NONE === json_last_error()) {
  127. return $errorHandler && false !== \call_user_func_array($errorHandler, \func_get_args());
  128. }
  129. });
  130. $data = json_encode($data, $this->encodingOptions);
  131. restore_error_handler();
  132. } else {
  133. $data = json_encode($data, $this->encodingOptions);
  134. }
  135. } catch (\Error $e) {
  136. if (\PHP_VERSION_ID < 50500 || !interface_exists('JsonSerializable', false)) {
  137. restore_error_handler();
  138. }
  139. throw $e;
  140. } catch (\Exception $e) {
  141. if (\PHP_VERSION_ID < 50500 || !interface_exists('JsonSerializable', false)) {
  142. restore_error_handler();
  143. }
  144. if (interface_exists('JsonSerializable', false) && 'Exception' === \get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
  145. throw $e->getPrevious() ?: $e;
  146. }
  147. throw $e;
  148. }
  149. }
  150. if (JSON_ERROR_NONE !== json_last_error()) {
  151. throw new \InvalidArgumentException(json_last_error_msg());
  152. }
  153. $this->data = $data;
  154. return $this->update();
  155. }
  156. /**
  157. * Returns options used while encoding data to JSON.
  158. *
  159. * @return int
  160. */
  161. public function getEncodingOptions()
  162. {
  163. return $this->encodingOptions;
  164. }
  165. /**
  166. * Sets options used while encoding data to JSON.
  167. *
  168. * @param int $encodingOptions
  169. *
  170. * @return $this
  171. */
  172. public function setEncodingOptions($encodingOptions)
  173. {
  174. $this->encodingOptions = (int) $encodingOptions;
  175. return $this->setData(json_decode($this->data));
  176. }
  177. /**
  178. * Updates the content and headers according to the JSON data and callback.
  179. *
  180. * @return $this
  181. */
  182. protected function update()
  183. {
  184. if (null !== $this->callback) {
  185. // Not using application/javascript for compatibility reasons with older browsers.
  186. $this->headers->set('Content-Type', 'text/javascript');
  187. return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data));
  188. }
  189. // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
  190. // in order to not overwrite a custom definition.
  191. if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) {
  192. $this->headers->set('Content-Type', 'application/json');
  193. }
  194. return $this->setContent($this->data);
  195. }
  196. }