| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
/*
|
|
|
4 |
* This file is part of the Symfony package.
|
|
|
5 |
*
|
|
|
6 |
* (c) Fabien Potencier <fabien@symfony.com>
|
|
|
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 <igor@wiedler.ch>
|
|
|
24 |
*/
|
|
|
25 |
class JsonResponse extends Response
|
|
|
26 |
{
|
|
|
27 |
protected $data;
|
|
|
28 |
protected $callback;
|
|
|
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 $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) && !\is_callable([$data, '__toString'])) {
|
|
|
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 = null): static
|
|
|
79 |
{
|
|
|
80 |
if (1 > \func_num_args()) {
|
|
|
81 |
trigger_deprecation('symfony/http-foundation', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
|
|
|
82 |
}
|
|
|
83 |
if (null !== $callback) {
|
|
|
84 |
// partially taken from https://geekality.net/2011/08/03/valid-javascript-identifier/
|
|
|
85 |
// partially taken from https://github.com/willdurand/JsonpCallbackValidator
|
|
|
86 |
// JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details.
|
|
|
87 |
// (c) William Durand <william.durand1@gmail.com>
|
|
|
88 |
$pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u';
|
|
|
89 |
$reserved = [
|
|
|
90 |
'break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while',
|
|
|
91 |
'debugger', 'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 'extends', 'super', 'const', 'export',
|
|
|
92 |
'import', 'implements', 'let', 'private', 'public', 'yield', 'interface', 'package', 'protected', 'static', 'null', 'true', 'false',
|
|
|
93 |
];
|
|
|
94 |
$parts = explode('.', $callback);
|
|
|
95 |
foreach ($parts as $part) {
|
|
|
96 |
if (!preg_match($pattern, $part) || \in_array($part, $reserved, true)) {
|
|
|
97 |
throw new \InvalidArgumentException('The callback name is not valid.');
|
|
|
98 |
}
|
|
|
99 |
}
|
|
|
100 |
}
|
|
|
101 |
|
|
|
102 |
$this->callback = $callback;
|
|
|
103 |
|
|
|
104 |
return $this->update();
|
|
|
105 |
}
|
|
|
106 |
|
|
|
107 |
/**
|
|
|
108 |
* Sets a raw string containing a JSON document to be sent.
|
|
|
109 |
*
|
|
|
110 |
* @return $this
|
|
|
111 |
*/
|
|
|
112 |
public function setJson(string $json): static
|
|
|
113 |
{
|
|
|
114 |
$this->data = $json;
|
|
|
115 |
|
|
|
116 |
return $this->update();
|
|
|
117 |
}
|
|
|
118 |
|
|
|
119 |
/**
|
|
|
120 |
* Sets the data to be sent as JSON.
|
|
|
121 |
*
|
|
|
122 |
* @return $this
|
|
|
123 |
*
|
|
|
124 |
* @throws \InvalidArgumentException
|
|
|
125 |
*/
|
|
|
126 |
public function setData(mixed $data = []): static
|
|
|
127 |
{
|
|
|
128 |
try {
|
|
|
129 |
$data = json_encode($data, $this->encodingOptions);
|
|
|
130 |
} catch (\Exception $e) {
|
|
|
131 |
if ('Exception' === $e::class && str_starts_with($e->getMessage(), 'Failed calling ')) {
|
|
|
132 |
throw $e->getPrevious() ?: $e;
|
|
|
133 |
}
|
|
|
134 |
throw $e;
|
|
|
135 |
}
|
|
|
136 |
|
|
|
137 |
if (\JSON_THROW_ON_ERROR & $this->encodingOptions) {
|
|
|
138 |
return $this->setJson($data);
|
|
|
139 |
}
|
|
|
140 |
|
|
|
141 |
if (\JSON_ERROR_NONE !== json_last_error()) {
|
|
|
142 |
throw new \InvalidArgumentException(json_last_error_msg());
|
|
|
143 |
}
|
|
|
144 |
|
|
|
145 |
return $this->setJson($data);
|
|
|
146 |
}
|
|
|
147 |
|
|
|
148 |
/**
|
|
|
149 |
* Returns options used while encoding data to JSON.
|
|
|
150 |
*/
|
|
|
151 |
public function getEncodingOptions(): int
|
|
|
152 |
{
|
|
|
153 |
return $this->encodingOptions;
|
|
|
154 |
}
|
|
|
155 |
|
|
|
156 |
/**
|
|
|
157 |
* Sets options used while encoding data to JSON.
|
|
|
158 |
*
|
|
|
159 |
* @return $this
|
|
|
160 |
*/
|
|
|
161 |
public function setEncodingOptions(int $encodingOptions): static
|
|
|
162 |
{
|
|
|
163 |
$this->encodingOptions = $encodingOptions;
|
|
|
164 |
|
|
|
165 |
return $this->setData(json_decode($this->data));
|
|
|
166 |
}
|
|
|
167 |
|
|
|
168 |
/**
|
|
|
169 |
* Updates the content and headers according to the JSON data and callback.
|
|
|
170 |
*
|
|
|
171 |
* @return $this
|
|
|
172 |
*/
|
|
|
173 |
protected function update(): static
|
|
|
174 |
{
|
|
|
175 |
if (null !== $this->callback) {
|
|
|
176 |
// Not using application/javascript for compatibility reasons with older browsers.
|
|
|
177 |
$this->headers->set('Content-Type', 'text/javascript');
|
|
|
178 |
|
|
|
179 |
return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data));
|
|
|
180 |
}
|
|
|
181 |
|
|
|
182 |
// Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
|
|
|
183 |
// in order to not overwrite a custom definition.
|
|
|
184 |
if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) {
|
|
|
185 |
$this->headers->set('Content-Type', 'application/json');
|
|
|
186 |
}
|
|
|
187 |
|
|
|
188 |
return $this->setContent($this->data);
|
|
|
189 |
}
|
|
|
190 |
}
|