Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\HttpFoundation; Chris@0: Chris@0: /** Chris@0: * Response represents an HTTP response in JSON format. Chris@0: * Chris@0: * Note that this class does not force the returned JSON content to be an Chris@0: * object. It is however recommended that you do return an object as it Chris@0: * protects yourself against XSSI and JSON-JavaScript Hijacking. Chris@0: * Chris@0: * @see https://www.owasp.org/index.php/OWASP_AJAX_Security_Guidelines#Always_return_JSON_with_an_Object_on_the_outside Chris@0: * Chris@0: * @author Igor Wiedler Chris@0: */ Chris@0: class JsonResponse extends Response Chris@0: { Chris@0: protected $data; Chris@0: protected $callback; Chris@0: Chris@0: // Encode <, >, ', &, and " characters in the JSON, making it also safe to be embedded into HTML. Chris@0: // 15 === JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT Chris@0: const DEFAULT_ENCODING_OPTIONS = 15; Chris@0: Chris@0: protected $encodingOptions = self::DEFAULT_ENCODING_OPTIONS; Chris@0: Chris@0: /** Chris@0: * @param mixed $data The response data Chris@0: * @param int $status The response status code Chris@0: * @param array $headers An array of response headers Chris@0: * @param bool $json If the data is already a JSON string Chris@0: */ Chris@17: public function __construct($data = null, $status = 200, $headers = [], $json = false) Chris@0: { Chris@0: parent::__construct('', $status, $headers); Chris@0: Chris@0: if (null === $data) { Chris@0: $data = new \ArrayObject(); Chris@0: } Chris@0: Chris@0: $json ? $this->setJson($data) : $this->setData($data); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Factory method for chainability. Chris@0: * Chris@0: * Example: Chris@0: * Chris@0: * return JsonResponse::create($data, 200) Chris@0: * ->setSharedMaxAge(300); Chris@0: * Chris@0: * @param mixed $data The json response data Chris@0: * @param int $status The response status code Chris@0: * @param array $headers An array of response headers Chris@0: * Chris@0: * @return static Chris@0: */ Chris@17: public static function create($data = null, $status = 200, $headers = []) Chris@0: { Chris@0: return new static($data, $status, $headers); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Make easier the creation of JsonResponse from raw json. Chris@0: */ Chris@17: public static function fromJsonString($data = null, $status = 200, $headers = []) Chris@0: { Chris@0: return new static($data, $status, $headers, true); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the JSONP callback. Chris@0: * Chris@0: * @param string|null $callback The JSONP callback or null to use none Chris@0: * Chris@0: * @return $this Chris@0: * Chris@0: * @throws \InvalidArgumentException When the callback name is not valid Chris@0: */ Chris@0: public function setCallback($callback = null) Chris@0: { Chris@0: if (null !== $callback) { Chris@0: // partially taken from http://www.geekality.net/2011/08/03/valid-javascript-identifier/ Chris@0: // partially taken from https://github.com/willdurand/JsonpCallbackValidator Chris@0: // JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details. Chris@0: // (c) William Durand Chris@0: $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u'; Chris@17: $reserved = [ Chris@0: 'break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while', Chris@0: 'debugger', 'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 'extends', 'super', 'const', 'export', Chris@0: 'import', 'implements', 'let', 'private', 'public', 'yield', 'interface', 'package', 'protected', 'static', 'null', 'true', 'false', Chris@17: ]; Chris@0: $parts = explode('.', $callback); Chris@0: foreach ($parts as $part) { Chris@17: if (!preg_match($pattern, $part) || \in_array($part, $reserved, true)) { Chris@0: throw new \InvalidArgumentException('The callback name is not valid.'); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: $this->callback = $callback; Chris@0: Chris@0: return $this->update(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets a raw string containing a JSON document to be sent. Chris@0: * Chris@0: * @param string $json Chris@0: * Chris@0: * @return $this Chris@0: * Chris@0: * @throws \InvalidArgumentException Chris@0: */ Chris@0: public function setJson($json) Chris@0: { Chris@0: $this->data = $json; Chris@0: Chris@0: return $this->update(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the data to be sent as JSON. Chris@0: * Chris@0: * @param mixed $data Chris@0: * Chris@0: * @return $this Chris@0: * Chris@0: * @throws \InvalidArgumentException Chris@0: */ Chris@17: public function setData($data = []) Chris@0: { Chris@17: if (\defined('HHVM_VERSION')) { Chris@0: // HHVM does not trigger any warnings and let exceptions Chris@0: // thrown from a JsonSerializable object pass through. Chris@0: // If only PHP did the same... Chris@0: $data = json_encode($data, $this->encodingOptions); Chris@0: } else { Chris@14: if (!interface_exists('JsonSerializable', false)) { Chris@14: set_error_handler(function () { return false; }); Chris@14: try { Chris@14: $data = @json_encode($data, $this->encodingOptions); Chris@14: } finally { Chris@14: restore_error_handler(); Chris@0: } Chris@14: } else { Chris@14: try { Chris@14: $data = json_encode($data, $this->encodingOptions); Chris@14: } catch (\Exception $e) { Chris@17: if ('Exception' === \get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) { Chris@14: throw $e->getPrevious() ?: $e; Chris@14: } Chris@14: throw $e; Chris@14: } Chris@0: } Chris@0: } Chris@0: Chris@0: if (JSON_ERROR_NONE !== json_last_error()) { Chris@0: throw new \InvalidArgumentException(json_last_error_msg()); Chris@0: } Chris@0: Chris@0: return $this->setJson($data); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns options used while encoding data to JSON. Chris@0: * Chris@0: * @return int Chris@0: */ Chris@0: public function getEncodingOptions() Chris@0: { Chris@0: return $this->encodingOptions; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets options used while encoding data to JSON. Chris@0: * Chris@0: * @param int $encodingOptions Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function setEncodingOptions($encodingOptions) Chris@0: { Chris@0: $this->encodingOptions = (int) $encodingOptions; Chris@0: Chris@0: return $this->setData(json_decode($this->data)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Updates the content and headers according to the JSON data and callback. Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: protected function update() Chris@0: { Chris@0: if (null !== $this->callback) { Chris@0: // Not using application/javascript for compatibility reasons with older browsers. Chris@0: $this->headers->set('Content-Type', 'text/javascript'); Chris@0: Chris@0: return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data)); Chris@0: } Chris@0: Chris@0: // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback) Chris@0: // in order to not overwrite a custom definition. Chris@0: if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) { Chris@0: $this->headers->set('Content-Type', 'application/json'); Chris@0: } Chris@0: Chris@0: return $this->setContent($this->data); Chris@0: } Chris@0: }