4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation;
15 * Response represents an HTTP response in JSON format.
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.
21 * @see https://www.owasp.org/index.php/OWASP_AJAX_Security_Guidelines#Always_return_JSON_with_an_Object_on_the_outside
23 * @author Igor Wiedler <igor@wiedler.ch>
25 class JsonResponse extends Response
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 protected $encodingOptions = 15;
37 * @param mixed $data The response data
38 * @param int $status The response status code
39 * @param array $headers An array of response headers
41 public function __construct($data = null, $status = 200, $headers = array())
43 parent::__construct('', $status, $headers);
46 $data = new \ArrayObject();
49 $this->setData($data);
53 * Factory method for chainability.
57 * return JsonResponse::create($data, 200)
58 * ->setSharedMaxAge(300);
60 * @param mixed $data The json response data
61 * @param int $status The response status code
62 * @param array $headers An array of response headers
66 public static function create($data = null, $status = 200, $headers = array())
68 return new static($data, $status, $headers);
72 * Sets the JSONP callback.
74 * @param string|null $callback The JSONP callback or null to use none
78 * @throws \InvalidArgumentException When the callback name is not valid
80 public function setCallback($callback = null)
82 if (null !== $callback) {
83 // partially token from http://www.geekality.net/2011/08/03/valid-javascript-identifier/
84 // partially token from https://github.com/willdurand/JsonpCallbackValidator
85 // JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details.
86 // (c) William Durand <william.durand1@gmail.com>
87 $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u';
89 'break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while',
90 'debugger', 'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 'extends', 'super', 'const', 'export',
91 'import', 'implements', 'let', 'private', 'public', 'yield', 'interface', 'package', 'protected', 'static', 'null', 'true', 'false',
93 $parts = explode('.', $callback);
94 foreach ($parts as $part) {
95 if (!preg_match($pattern, $part) || in_array($part, $reserved, true)) {
96 throw new \InvalidArgumentException('The callback name is not valid.');
101 $this->callback = $callback;
103 return $this->update();
107 * Sets the data to be sent as JSON.
113 * @throws \InvalidArgumentException
115 public function setData($data = array())
117 if (defined('HHVM_VERSION')) {
118 // HHVM does not trigger any warnings and let exceptions
119 // thrown from a JsonSerializable object pass through.
120 // If only PHP did the same...
121 $data = json_encode($data, $this->encodingOptions);
124 if (\PHP_VERSION_ID < 50400) {
125 // PHP 5.3 triggers annoying warnings for some
126 // types that can't be serialized as JSON (INF, resources, etc.)
127 // but doesn't provide the JsonSerializable interface.
128 set_error_handler(function () { return false; });
129 $data = @json_encode($data, $this->encodingOptions);
131 // PHP 5.4 and up wrap exceptions thrown by JsonSerializable
132 // objects in a new exception that needs to be removed.
133 // Fortunately, PHP 5.5 and up do not trigger any warning anymore.
134 if (\PHP_VERSION_ID < 50500) {
135 // Clear json_last_error()
137 $errorHandler = set_error_handler('var_dump');
138 restore_error_handler();
139 set_error_handler(function () use ($errorHandler) {
140 if (JSON_ERROR_NONE === json_last_error()) {
141 return $errorHandler && false !== call_user_func_array($errorHandler, func_get_args());
146 $data = json_encode($data, $this->encodingOptions);
149 if (\PHP_VERSION_ID < 50500) {
150 restore_error_handler();
152 } catch (\Exception $e) {
153 if (\PHP_VERSION_ID < 50500) {
154 restore_error_handler();
156 if (\PHP_VERSION_ID >= 50400 && 'Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
157 throw $e->getPrevious() ?: $e;
163 if (JSON_ERROR_NONE !== json_last_error()) {
164 throw new \InvalidArgumentException(json_last_error_msg());
169 return $this->update();
173 * Returns options used while encoding data to JSON.
177 public function getEncodingOptions()
179 return $this->encodingOptions;
183 * Sets options used while encoding data to JSON.
185 * @param int $encodingOptions
189 public function setEncodingOptions($encodingOptions)
191 $this->encodingOptions = (int) $encodingOptions;
193 return $this->setData(json_decode($this->data));
197 * Updates the content and headers according to the JSON data and callback.
201 protected function update()
203 if (null !== $this->callback) {
204 // Not using application/javascript for compatibility reasons with older browsers.
205 $this->headers->set('Content-Type', 'text/javascript');
207 return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data));
210 // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
211 // in order to not overwrite a custom definition.
212 if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) {
213 $this->headers->set('Content-Type', 'application/json');
216 return $this->setContent($this->data);