cf1a11ea2c07b690939d7b19600c5b668c0ee54b
[yaffs-website] / vendor / symfony / http-foundation / JsonResponse.php
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://www.owasp.org/index.php/OWASP_AJAX_Security_Guidelines#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     const DEFAULT_ENCODING_OPTIONS = 15;
33
34     protected $encodingOptions = self::DEFAULT_ENCODING_OPTIONS;
35
36     /**
37      * @param mixed $data    The response data
38      * @param int   $status  The response status code
39      * @param array $headers An array of response headers
40      * @param bool  $json    If the data is already a JSON string
41      */
42     public function __construct($data = null, $status = 200, $headers = array(), $json = false)
43     {
44         parent::__construct('', $status, $headers);
45
46         if (null === $data) {
47             $data = new \ArrayObject();
48         }
49
50         $json ? $this->setJson($data) : $this->setData($data);
51     }
52
53     /**
54      * Factory method for chainability.
55      *
56      * Example:
57      *
58      *     return JsonResponse::create($data, 200)
59      *         ->setSharedMaxAge(300);
60      *
61      * @param mixed $data    The json response data
62      * @param int   $status  The response status code
63      * @param array $headers An array of response headers
64      *
65      * @return static
66      */
67     public static function create($data = null, $status = 200, $headers = array())
68     {
69         return new static($data, $status, $headers);
70     }
71
72     /**
73      * Make easier the creation of JsonResponse from raw json.
74      */
75     public static function fromJsonString($data = null, $status = 200, $headers = array())
76     {
77         return new static($data, $status, $headers, true);
78     }
79
80     /**
81      * Sets the JSONP callback.
82      *
83      * @param string|null $callback The JSONP callback or null to use none
84      *
85      * @return $this
86      *
87      * @throws \InvalidArgumentException When the callback name is not valid
88      */
89     public function setCallback($callback = null)
90     {
91         if (null !== $callback) {
92             // partially taken from http://www.geekality.net/2011/08/03/valid-javascript-identifier/
93             // partially taken from https://github.com/willdurand/JsonpCallbackValidator
94             //      JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details.
95             //      (c) William Durand <william.durand1@gmail.com>
96             $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u';
97             $reserved = array(
98                 'break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while',
99                 'debugger', 'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 'extends', 'super',  'const', 'export',
100                 'import', 'implements', 'let', 'private', 'public', 'yield', 'interface', 'package', 'protected', 'static', 'null', 'true', 'false',
101             );
102             $parts = explode('.', $callback);
103             foreach ($parts as $part) {
104                 if (!preg_match($pattern, $part) || in_array($part, $reserved, true)) {
105                     throw new \InvalidArgumentException('The callback name is not valid.');
106                 }
107             }
108         }
109
110         $this->callback = $callback;
111
112         return $this->update();
113     }
114
115     /**
116      * Sets a raw string containing a JSON document to be sent.
117      *
118      * @param string $json
119      *
120      * @return $this
121      *
122      * @throws \InvalidArgumentException
123      */
124     public function setJson($json)
125     {
126         $this->data = $json;
127
128         return $this->update();
129     }
130
131     /**
132      * Sets the data to be sent as JSON.
133      *
134      * @param mixed $data
135      *
136      * @return $this
137      *
138      * @throws \InvalidArgumentException
139      */
140     public function setData($data = array())
141     {
142         if (defined('HHVM_VERSION')) {
143             // HHVM does not trigger any warnings and let exceptions
144             // thrown from a JsonSerializable object pass through.
145             // If only PHP did the same...
146             $data = json_encode($data, $this->encodingOptions);
147         } else {
148             try {
149                 // PHP 5.4 and up wrap exceptions thrown by JsonSerializable
150                 // objects in a new exception that needs to be removed.
151                 // Fortunately, PHP 5.5 and up do not trigger any warning anymore.
152                 $data = json_encode($data, $this->encodingOptions);
153             } catch (\Exception $e) {
154                 if ('Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
155                     throw $e->getPrevious() ?: $e;
156                 }
157                 throw $e;
158             }
159         }
160
161         if (JSON_ERROR_NONE !== json_last_error()) {
162             throw new \InvalidArgumentException(json_last_error_msg());
163         }
164
165         return $this->setJson($data);
166     }
167
168     /**
169      * Returns options used while encoding data to JSON.
170      *
171      * @return int
172      */
173     public function getEncodingOptions()
174     {
175         return $this->encodingOptions;
176     }
177
178     /**
179      * Sets options used while encoding data to JSON.
180      *
181      * @param int $encodingOptions
182      *
183      * @return $this
184      */
185     public function setEncodingOptions($encodingOptions)
186     {
187         $this->encodingOptions = (int) $encodingOptions;
188
189         return $this->setData(json_decode($this->data));
190     }
191
192     /**
193      * Updates the content and headers according to the JSON data and callback.
194      *
195      * @return $this
196      */
197     protected function update()
198     {
199         if (null !== $this->callback) {
200             // Not using application/javascript for compatibility reasons with older browsers.
201             $this->headers->set('Content-Type', 'text/javascript');
202
203             return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data));
204         }
205
206         // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
207         // in order to not overwrite a custom definition.
208         if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) {
209             $this->headers->set('Content-Type', 'application/json');
210         }
211
212         return $this->setContent($this->data);
213     }
214 }