JsonResponse.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 " for RFC4627-compliant JSON, which may also be embedded into HTML.
  27. // 15 === JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
  28. protected $encodingOptions = 15;
  29. /**
  30. * Constructor.
  31. *
  32. * @param mixed $data The response data
  33. * @param int $status The response status code
  34. * @param array $headers An array of response headers
  35. */
  36. public function __construct($data = null, $status = 200, $headers = array())
  37. {
  38. parent::__construct('', $status, $headers);
  39. if (null === $data) {
  40. $data = new \ArrayObject();
  41. }
  42. $this->setData($data);
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public static function create($data = null, $status = 200, $headers = array())
  48. {
  49. return new static($data, $status, $headers);
  50. }
  51. /**
  52. * Sets the JSONP callback.
  53. *
  54. * @param string|null $callback The JSONP callback or null to use none
  55. *
  56. * @return JsonResponse
  57. *
  58. * @throws \InvalidArgumentException When the callback name is not valid
  59. */
  60. public function setCallback($callback = null)
  61. {
  62. if (null !== $callback) {
  63. // taken from http://www.geekality.net/2011/08/03/valid-javascript-identifier/
  64. $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*+$/u';
  65. $parts = explode('.', $callback);
  66. foreach ($parts as $part) {
  67. if (!preg_match($pattern, $part)) {
  68. throw new \InvalidArgumentException('The callback name is not valid.');
  69. }
  70. }
  71. }
  72. $this->callback = $callback;
  73. return $this->update();
  74. }
  75. /**
  76. * Sets the data to be sent as JSON.
  77. *
  78. * @param mixed $data
  79. *
  80. * @return JsonResponse
  81. *
  82. * @throws \InvalidArgumentException
  83. */
  84. public function setData($data = array())
  85. {
  86. if (defined('HHVM_VERSION')) {
  87. // HHVM does not trigger any warnings and let exceptions
  88. // thrown from a JsonSerializable object pass through.
  89. // If only PHP did the same...
  90. $data = json_encode($data, $this->encodingOptions);
  91. } else {
  92. try {
  93. if (PHP_VERSION_ID < 50400) {
  94. // PHP 5.3 triggers annoying warnings for some
  95. // types that can't be serialized as JSON (INF, resources, etc.)
  96. // but doesn't provide the JsonSerializable interface.
  97. set_error_handler(function () { return false; });
  98. $data = @json_encode($data, $this->encodingOptions);
  99. } else {
  100. // PHP 5.4 and up wrap exceptions thrown by JsonSerializable
  101. // objects in a new exception that needs to be removed.
  102. // Fortunately, PHP 5.5 and up do not trigger any warning anymore.
  103. if (PHP_VERSION_ID < 50500) {
  104. // Clear json_last_error()
  105. json_encode(null);
  106. $errorHandler = set_error_handler('var_dump');
  107. restore_error_handler();
  108. set_error_handler(function () use ($errorHandler) {
  109. if (JSON_ERROR_NONE === json_last_error()) {
  110. return $errorHandler && false !== call_user_func_array($errorHandler, func_get_args());
  111. }
  112. });
  113. }
  114. $data = json_encode($data, $this->encodingOptions);
  115. }
  116. if (PHP_VERSION_ID < 50500) {
  117. restore_error_handler();
  118. }
  119. } catch (\Exception $e) {
  120. if (PHP_VERSION_ID < 50500) {
  121. restore_error_handler();
  122. }
  123. if (PHP_VERSION_ID >= 50400 && 'Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
  124. throw $e->getPrevious() ?: $e;
  125. }
  126. throw $e;
  127. }
  128. }
  129. if (JSON_ERROR_NONE !== json_last_error()) {
  130. throw new \InvalidArgumentException(json_last_error_msg());
  131. }
  132. $this->data = $data;
  133. return $this->update();
  134. }
  135. /**
  136. * Returns options used while encoding data to JSON.
  137. *
  138. * @return int
  139. */
  140. public function getEncodingOptions()
  141. {
  142. return $this->encodingOptions;
  143. }
  144. /**
  145. * Sets options used while encoding data to JSON.
  146. *
  147. * @param int $encodingOptions
  148. *
  149. * @return JsonResponse
  150. */
  151. public function setEncodingOptions($encodingOptions)
  152. {
  153. $this->encodingOptions = (int) $encodingOptions;
  154. return $this->setData(json_decode($this->data));
  155. }
  156. /**
  157. * Updates the content and headers according to the JSON data and callback.
  158. *
  159. * @return JsonResponse
  160. */
  161. protected function update()
  162. {
  163. if (null !== $this->callback) {
  164. // Not using application/javascript for compatibility reasons with older browsers.
  165. $this->headers->set('Content-Type', 'text/javascript');
  166. return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data));
  167. }
  168. // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
  169. // in order to not overwrite a custom definition.
  170. if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) {
  171. $this->headers->set('Content-Type', 'application/json');
  172. }
  173. return $this->setContent($this->data);
  174. }
  175. }