classJsonResponseextendsResponse { /** * @param mixed $data The response data * @param int $status The response status code * @param array $headers An array of response headers * @param bool $json If the data is already a JSON string */ publicfunction__construct($data = null, int $status = 200, array $headers = [], bool $json = false) { parent::__construct('', $status, $headers);
// 如果没有返回数据,则 new 一个 if (null === $data) { $data = new \ArrayObject(); }
/** * Updates the content and headers according to the JSON data and callback. * 根据 json 数据和 callback 内容 配置 content 和 headers * * @return $this */ protectedfunctionupdate() { if (null !== $this->callback) { // Not using application/javascript for compatibility reasons with older browsers. $this->headers->set('Content-Type', 'text/javascript');
// Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback) // in order to not overwrite a custom definition. // 如果没有配置 Content-Type 或者 Content-Type 为 text/javascript 时,更新为 application/json if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) { $this->headers->set('Content-Type', 'application/json'); }
// remove headers that MUST NOT be included with 304 Not Modified responses foreach (['Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified'] as $header) { $this->headers->remove($header); }
/** * Prepares the Response before it is sent to the client. * * This method tweaks the Response to ensure that it is * compliant with RFC 2616. Most of the changes are based on * the Request that is "associated" with this Response. * * @return $this */ publicfunctionprepare(Request $request) { $headers = $this->headers;
// Check if we need to send extra expire info headers if ('1.0' == $this->getProtocolVersion() && false !== strpos($headers->get('Cache-Control'), 'no-cache')) { $headers->set('pragma', 'no-cache'); $headers->set('expires', -1); }
// Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9. // 用户使用 IE9 以下的浏览器时,要检查是否为 SSL 加密下载移除 Cache-Control $this->ensureIEOverSSLCompatibility($request);
// 检查是否信任的代理并且 X-Forwarded-Proto 的协议为 https、on、ssl或1 if ($request->isSecure()) { foreach ($headers->getCookies() as $cookie) { $cookie->setSecureDefault(true); } }