Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/JsonResponse.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpFoundation;
13
14 /**
15 * Response represents an HTTP response in JSON format.
16 *
17 * Note that this class does not force the returned JSON content to be an
18 * object. It is however recommended that you do return an object as it
19 * protects yourself against XSSI and JSON-JavaScript Hijacking.
20 *
21 * @see https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/AJAX_Security_Cheat_Sheet.md#always-return-json-with-an-object-on-the-outside
22 *
23 * @author Igor Wiedler <[email protected]>
24 */
25 class JsonResponse extends Response
26 {
27 protected mixed $data;
28 protected ?string $callback = null;
29
30 // Encode <, >, ', &, and " characters in the JSON, making it also safe to be embedded into HTML.
31 // 15 === JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
32 public const DEFAULT_ENCODING_OPTIONS = 15;
33
34 protected int $encodingOptions = self::DEFAULT_ENCODING_OPTIONS;
35
36 /**
37 * @param bool $json If the data is already a JSON string
38 */
39 public function __construct(mixed $data = null, int $status = 200, array $headers = [], bool $json = false)
40 {
41 parent::__construct('', $status, $headers);
42
43 if ($json && !\is_string($data) && !is_numeric($data) && !$data instanceof \Stringable) {
44 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)));
45 }
46
47 $data ??= new \ArrayObject();
48
49 $json ? $this->setJson($data) : $this->setData($data);
50 }
51
52 /**
53 * Factory method for chainability.
54 *
55 * Example:
56 *
57 * return JsonResponse::fromJsonString('{"key": "value"}')
58 * ->setSharedMaxAge(300);
59 *
60 * @param string $data The JSON response string
61 * @param int $status The response status code (200 "OK" by default)
62 * @param array $headers An array of response headers
63 */
64 public static function fromJsonString(string $data, int $status = 200, array $headers = []): static
65 {
66 return new static($data, $status, $headers, true);
67 }
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(?string $callback): static
79 {
80 if (null !== $callback) {
81 // partially taken from https://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 <[email protected]>
85 $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u';
86 $reserved = [
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
99 $this->callback = $callback;
100
101 return $this->update();
102 }
103
104 /**
105 * Sets a raw string containing a JSON document to be sent.
106 *
107 * @return $this
108 */
109 public function setJson(string $json): static
110 {
111 $this->data = $json;
112
113 return $this->update();
114 }
115
116 /**
117 * Sets the data to be sent as JSON.
118 *
119 * @return $this
120 *
121 * @throws \InvalidArgumentException
122 */
123 public function setData(mixed $data = []): static
124 {
125 try {
126 $data = json_encode($data, $this->encodingOptions);
127 } catch (\Exception $e) {
128 if ('Exception' === $e::class && str_starts_with($e->getMessage(), 'Failed calling ')) {
129 throw $e->getPrevious() ?: $e;
130 }
131 throw $e;
132 }
133
134 if (\JSON_THROW_ON_ERROR & $this->encodingOptions) {
135 return $this->setJson($data);
136 }
137
138 if (\JSON_ERROR_NONE !== json_last_error()) {
139 throw new \InvalidArgumentException(json_last_error_msg());
140 }
141
142 return $this->setJson($data);
143 }
144
145 /**
146 * Returns options used while encoding data to JSON.
147 */
148 public function getEncodingOptions(): int
149 {
150 return $this->encodingOptions;
151 }
152
153 /**
154 * Sets options used while encoding data to JSON.
155 *
156 * @return $this
157 */
158 public function setEncodingOptions(int $encodingOptions): static
159 {
160 $this->encodingOptions = $encodingOptions;
161
162 return $this->setData(json_decode($this->data));
163 }
164
165 /**
166 * Updates the content and headers according to the JSON data and callback.
167 *
168 * @return $this
169 */
170 protected function update(): static
171 {
172 if (null !== $this->callback) {
173 // Not using application/javascript for compatibility reasons with older browsers.
174 $this->headers->set('Content-Type', 'text/javascript');
175
176 return $this->setContent(\sprintf('/**/%s(%s);', $this->callback, $this->data));
177 }
178
179 // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
180 // in order to not overwrite a custom definition.
181 if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) {
182 $this->headers->set('Content-Type', 'application/json');
183 }
184
185 return $this->setContent($this->data);
186 }
187 }