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 * ResponseHeaderBag is a container for Response HTTP headers.
17 * @author Fabien Potencier <fabien@symfony.com>
19 class ResponseHeaderBag extends HeaderBag
21 const COOKIES_FLAT = 'flat';
22 const COOKIES_ARRAY = 'array';
24 const DISPOSITION_ATTACHMENT = 'attachment';
25 const DISPOSITION_INLINE = 'inline';
30 protected $computedCacheControl = array();
35 protected $cookies = array();
40 protected $headerNames = array();
45 * @param array $headers An array of HTTP headers
47 public function __construct(array $headers = array())
49 parent::__construct($headers);
51 if (!isset($this->headers['cache-control'])) {
52 $this->set('Cache-Control', '');
59 public function __toString()
62 foreach ($this->getCookies() as $cookie) {
63 $cookies .= 'Set-Cookie: '.$cookie."\r\n";
66 ksort($this->headerNames);
68 return parent::__toString().$cookies;
72 * Returns the headers, with original capitalizations.
74 * @return array An array of headers
76 public function allPreserveCase()
78 return array_combine($this->headerNames, $this->headers);
84 public function replace(array $headers = array())
86 $this->headerNames = array();
88 parent::replace($headers);
90 if (!isset($this->headers['cache-control'])) {
91 $this->set('Cache-Control', '');
98 public function set($key, $values, $replace = true)
100 parent::set($key, $values, $replace);
102 $uniqueKey = str_replace('_', '-', strtolower($key));
103 $this->headerNames[$uniqueKey] = $key;
105 // ensure the cache-control header has sensible defaults
106 if (in_array($uniqueKey, array('cache-control', 'etag', 'last-modified', 'expires'))) {
107 $computed = $this->computeCacheControlValue();
108 $this->headers['cache-control'] = array($computed);
109 $this->headerNames['cache-control'] = 'Cache-Control';
110 $this->computedCacheControl = $this->parseCacheControl($computed);
117 public function remove($key)
119 parent::remove($key);
121 $uniqueKey = str_replace('_', '-', strtolower($key));
122 unset($this->headerNames[$uniqueKey]);
124 if ('cache-control' === $uniqueKey) {
125 $this->computedCacheControl = array();
132 public function hasCacheControlDirective($key)
134 return array_key_exists($key, $this->computedCacheControl);
140 public function getCacheControlDirective($key)
142 return array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null;
148 * @param Cookie $cookie
150 public function setCookie(Cookie $cookie)
152 $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
156 * Removes a cookie from the array, but does not unset it in the browser.
158 * @param string $name
159 * @param string $path
160 * @param string $domain
162 public function removeCookie($name, $path = '/', $domain = null)
164 if (null === $path) {
168 unset($this->cookies[$domain][$path][$name]);
170 if (empty($this->cookies[$domain][$path])) {
171 unset($this->cookies[$domain][$path]);
173 if (empty($this->cookies[$domain])) {
174 unset($this->cookies[$domain]);
180 * Returns an array with all cookies.
182 * @param string $format
186 * @throws \InvalidArgumentException When the $format is invalid
188 public function getCookies($format = self::COOKIES_FLAT)
190 if (!in_array($format, array(self::COOKIES_FLAT, self::COOKIES_ARRAY))) {
191 throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', array(self::COOKIES_FLAT, self::COOKIES_ARRAY))));
194 if (self::COOKIES_ARRAY === $format) {
195 return $this->cookies;
198 $flattenedCookies = array();
199 foreach ($this->cookies as $path) {
200 foreach ($path as $cookies) {
201 foreach ($cookies as $cookie) {
202 $flattenedCookies[] = $cookie;
207 return $flattenedCookies;
211 * Clears a cookie in the browser.
213 * @param string $name
214 * @param string $path
215 * @param string $domain
216 * @param bool $secure
217 * @param bool $httpOnly
219 public function clearCookie($name, $path = '/', $domain = null, $secure = false, $httpOnly = true)
221 $this->setCookie(new Cookie($name, null, 1, $path, $domain, $secure, $httpOnly));
225 * Generates a HTTP Content-Disposition field-value.
227 * @param string $disposition One of "inline" or "attachment"
228 * @param string $filename A unicode string
229 * @param string $filenameFallback A string containing only ASCII characters that
230 * is semantically equivalent to $filename. If the filename is already ASCII,
231 * it can be omitted, or just copied from $filename
233 * @return string A string suitable for use as a Content-Disposition field-value
235 * @throws \InvalidArgumentException
239 public function makeDisposition($disposition, $filename, $filenameFallback = '')
241 if (!in_array($disposition, array(self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE))) {
242 throw new \InvalidArgumentException(sprintf('The disposition must be either "%s" or "%s".', self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE));
245 if ('' == $filenameFallback) {
246 $filenameFallback = $filename;
249 // filenameFallback is not ASCII.
250 if (!preg_match('/^[\x20-\x7e]*$/', $filenameFallback)) {
251 throw new \InvalidArgumentException('The filename fallback must only contain ASCII characters.');
254 // percent characters aren't safe in fallback.
255 if (false !== strpos($filenameFallback, '%')) {
256 throw new \InvalidArgumentException('The filename fallback cannot contain the "%" character.');
259 // path separators aren't allowed in either.
260 if (false !== strpos($filename, '/') || false !== strpos($filename, '\\') || false !== strpos($filenameFallback, '/') || false !== strpos($filenameFallback, '\\')) {
261 throw new \InvalidArgumentException('The filename and the fallback cannot contain the "/" and "\\" characters.');
264 $output = sprintf('%s; filename="%s"', $disposition, str_replace('"', '\\"', $filenameFallback));
266 if ($filename !== $filenameFallback) {
267 $output .= sprintf("; filename*=utf-8''%s", rawurlencode($filename));
274 * Returns the calculated value of the cache-control header.
276 * This considers several other headers and calculates or modifies the
277 * cache-control header to a sensible, conservative value.
281 protected function computeCacheControlValue()
283 if (!$this->cacheControl && !$this->has('ETag') && !$this->has('Last-Modified') && !$this->has('Expires')) {
287 if (!$this->cacheControl) {
288 // conservative by default
289 return 'private, must-revalidate';
292 $header = $this->getCacheControlHeader();
293 if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) {
297 // public if s-maxage is defined, private otherwise
298 if (!isset($this->cacheControl['s-maxage'])) {
299 return $header.', private';