JsonResponse.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. public const DEFAULT_ENCODING_OPTIONS = 15;
  29. protected $encodingOptions = self::DEFAULT_ENCODING_OPTIONS;
  30. /**
  31. * @param bool $json If the data is already a JSON string
  32. */
  33. public function __construct(mixed $data = null, int $status = 200, array $headers = [], bool $json = false)
  34. {
  35. parent::__construct('', $status, $headers);
  36. if ($json && !\is_string($data) && !is_numeric($data) && !\is_callable([$data, '__toString'])) {
  37. throw new \TypeError(sprintf('"%s": If $json is set to true, argument $data must be a string or object implementing __toString(), "%s" given.', __METHOD__, get_debug_type($data)));
  38. }
  39. $data ??= new \ArrayObject();
  40. $json ? $this->setJson($data) : $this->setData($data);
  41. }
  42. /**
  43. * Factory method for chainability.
  44. *
  45. * Example:
  46. *
  47. * return JsonResponse::fromJsonString('{"key": "value"}')
  48. * ->setSharedMaxAge(300);
  49. *
  50. * @param string $data The JSON response string
  51. * @param int $status The response status code (200 "OK" by default)
  52. * @param array $headers An array of response headers
  53. */
  54. public static function fromJsonString(string $data, int $status = 200, array $headers = []): static
  55. {
  56. return new static($data, $status, $headers, true);
  57. }
  58. /**
  59. * Sets the JSONP callback.
  60. *
  61. * @param string|null $callback The JSONP callback or null to use none
  62. *
  63. * @return $this
  64. *
  65. * @throws \InvalidArgumentException When the callback name is not valid
  66. */
  67. public function setCallback(?string $callback = null): static
  68. {
  69. if (1 > \func_num_args()) {
  70. trigger_deprecation('symfony/http-foundation', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
  71. }
  72. if (null !== $callback) {
  73. // partially taken from https://geekality.net/2011/08/03/valid-javascript-identifier/
  74. // partially taken from https://github.com/willdurand/JsonpCallbackValidator
  75. // JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details.
  76. // (c) William Durand <william.durand1@gmail.com>
  77. $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u';
  78. $reserved = [
  79. 'break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while',
  80. 'debugger', 'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 'extends', 'super', 'const', 'export',
  81. 'import', 'implements', 'let', 'private', 'public', 'yield', 'interface', 'package', 'protected', 'static', 'null', 'true', 'false',
  82. ];
  83. $parts = explode('.', $callback);
  84. foreach ($parts as $part) {
  85. if (!preg_match($pattern, $part) || \in_array($part, $reserved, true)) {
  86. throw new \InvalidArgumentException('The callback name is not valid.');
  87. }
  88. }
  89. }
  90. $this->callback = $callback;
  91. return $this->update();
  92. }
  93. /**
  94. * Sets a raw string containing a JSON document to be sent.
  95. *
  96. * @return $this
  97. */
  98. public function setJson(string $json): static
  99. {
  100. $this->data = $json;
  101. return $this->update();
  102. }
  103. /**
  104. * Sets the data to be sent as JSON.
  105. *
  106. * @return $this
  107. *
  108. * @throws \InvalidArgumentException
  109. */
  110. public function setData(mixed $data = []): static
  111. {
  112. try {
  113. $data = json_encode($data, $this->encodingOptions);
  114. } catch (\Exception $e) {
  115. if ('Exception' === $e::class && str_starts_with($e->getMessage(), 'Failed calling ')) {
  116. throw $e->getPrevious() ?: $e;
  117. }
  118. throw $e;
  119. }
  120. if (\JSON_THROW_ON_ERROR & $this->encodingOptions) {
  121. return $this->setJson($data);
  122. }
  123. if (\JSON_ERROR_NONE !== json_last_error()) {
  124. throw new \InvalidArgumentException(json_last_error_msg());
  125. }
  126. return $this->setJson($data);
  127. }
  128. /**
  129. * Returns options used while encoding data to JSON.
  130. */
  131. public function getEncodingOptions(): int
  132. {
  133. return $this->encodingOptions;
  134. }
  135. /**
  136. * Sets options used while encoding data to JSON.
  137. *
  138. * @return $this
  139. */
  140. public function setEncodingOptions(int $encodingOptions): static
  141. {
  142. $this->encodingOptions = $encodingOptions;
  143. return $this->setData(json_decode($this->data));
  144. }
  145. /**
  146. * Updates the content and headers according to the JSON data and callback.
  147. *
  148. * @return $this
  149. */
  150. protected function update(): static
  151. {
  152. if (null !== $this->callback) {
  153. // Not using application/javascript for compatibility reasons with older browsers.
  154. $this->headers->set('Content-Type', 'text/javascript');
  155. return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data));
  156. }
  157. // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
  158. // in order to not overwrite a custom definition.
  159. if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) {
  160. $this->headers->set('Content-Type', 'application/json');
  161. }
  162. return $this->setContent($this->data);
  163. }
  164. }