[RequestHandler] added a bunch of HTTP cache related methods to the Response class

This commit is contained in:
Fabien Potencier 2010-05-03 11:47:01 +02:00
parent c34da5d6c4
commit 606e44e491
2 changed files with 596 additions and 0 deletions

View File

@ -270,4 +270,443 @@ class Response
{
return $this->statusCode;
}
/**
* Returns true if the response is worth caching under any circumstance.
*
* Responses marked "private" with an explicit Cache-Control directive are
* considered uncacheable.
*
* Responses with neither a freshness lifetime (Expires, max-age) nor cache
* validator (Last-Modified, ETag) are considered uncacheable.
*
* @return Boolean true if the response is worth caching, false otherwise
*/
public function isCacheable()
{
if (!in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410)))
{
return false;
}
if ($this->headers->getCacheControl()->isNoStore() || $this->headers->getCacheControl()->isPrivate())
{
return false;
}
return $this->isValidateable() || $this->isFresh();
}
/**
* Returns true if the response is "fresh".
*
* Fresh responses may be served from cache without any interaction with the
* origin. A response is considered fresh when it includes a Cache-Control/max-age
* indicator or Expiration header and the calculated age is less than the freshness lifetime.
*
* @return Boolean true if the response is fresh, false otherwise
*/
public function isFresh()
{
return $this->getTtl() > 0;
}
/**
* Returns true if the response includes headers that can be used to validate
* the response with the origin server using a conditional GET request.
*
* @return Boolean true if the response is validateable, false otherwise
*/
public function isValidateable()
{
return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
}
/**
* Marks the response "private".
*
* It makes the response ineligible for serving other clients.
*
* @param Boolean $value Whether to set the response to be private or public.
*/
public function setPrivate($value)
{
$value = (Boolean) $value;
$this->headers->getCacheControl()->setPublic(!$value);
$this->headers->getCacheControl()->setPrivate($value);
}
/**
* Returns true if the response must be revalidated by caches.
*
* This method indicates that the response must not be served stale by a
* cache in any circumstance without first revalidating with the origin.
* When present, the TTL of the response should not be overriden to be
* greater than the value provided by the origin.
*
* @return Boolean true if the response must be revalidated by a cache, false otherwise
*/
public function mustRevalidate()
{
return $this->headers->getCacheControl()->mustRevalidate() || $this->headers->getCacheControl()->mustProxyRevalidate();
}
/**
* Returns the Date header as a DateTime instance.
*
* When no Date header is present, the current time is returned.
*
* @return \DateTime A \DateTime instance
*
* @throws \RuntimeException when the header is not parseable
*/
public function getDate()
{
if (null === $date = $this->headers->getDate('Date'))
{
$date = new \DateTime();
$this->headers->set('Date', $date->format(DATE_RFC2822));
}
return $date;
}
/**
* Returns the age of the response.
*
* @return integer The age of the response in seconds
*/
public function getAge()
{
if ($age = $this->headers->get('Age'))
{
return $age;
}
return max(time() - $this->getDate()->format('U'), 0);
}
/**
* Marks the response stale by setting the Age header to be equal to the maximum age of the response.
*/
public function expire()
{
if ($this->isFresh())
{
$this->headers->set('Age', $this->getMaxAge());
}
}
/**
* Returns the value of the Expires header as a DateTime instance.
*
* @return \DateTime A DateTime instance
*/
public function getExpires()
{
return $this->headers->getDate('Expires');
}
/**
* Sets the Expires HTTP header with a \DateTime instance.
*
* If passed a null value, it deletes the header.
*
* @param \DateTime $date A \DateTime instance
*/
public function setExpires(\DateTime $date = null)
{
if (null === $date)
{
$this->headers->delete('Expires');
}
else
{
$this->headers->set('Expires', $date->format(DATE_RFC2822));
}
}
/**
* Sets the number of seconds after the time specified in the response's Date
* header when the the response should no longer be considered fresh.
*
* First, it checks for a s-maxage directive, then a max-age directive, and then it falls
* back on an expires header. It returns null when no maximum age can be established.
*
* @return integer|null Number of seconds
*/
public function getMaxAge()
{
if ($age = $this->headers->getCacheControl()->getSharedMaxAge())
{
return $age;
}
if ($age = $this->headers->getCacheControl()->getMaxAge())
{
return $age;
}
if (null !== $this->getExpires())
{
return $this->getExpires()->format('U') - $this->getDate()->format('U');
}
return null;
}
/**
* Sets the number of seconds after which the response should no longer be considered fresh.
*
* This methods sets the Cache-Control max-age directive.
*
* @param integer $value A number of seconds
*/
public function setMaxAge($value)
{
$this->headers->getCacheControl()->setMaxAge($value);
}
/**
* Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
*
* This methods sets the Cache-Control s-maxage directive.
*
* @param integer $value A number of seconds
*/
public function setSharedMaxAge($value)
{
$this->headers->getCacheControl()->setSharedMaxAge($value);
}
/**
* Returns the response's time-to-live in seconds.
*
* It returns null when no freshness information is present in the response.
*
* When the responses TTL is <= 0, the response may not be served from cache without first
* revalidating with the origin.
*
* @return integer The TTL in seconds
*/
public function getTtl()
{
if ($maxAge = $this->getMaxAge())
{
return $maxAge - $this->getAge();
}
return null;
}
/**
* Sets the response's time-to-live for shared caches.
*
* This method adjusts the Cache-Control/s-maxage directive.
*
* @param integer $seconds The number of seconds
*/
public function setTtl($seconds)
{
$this->setSharedMaxAge($this->getAge() + $seconds);
}
/**
* Sets the response's time-to-live for private/client caches.
*
* This method adjusts the Cache-Control/max-age directive.
*
* @param integer $seconds The number of seconds
*/
public function setClientTtl($seconds)
{
$this->setMaxAge($this->getAge() + $seconds);
}
/**
* Returns the Last-Modified HTTP header as a DateTime instance.
*
* @return \DateTime A DateTime instance
*/
public function getLastModified()
{
return $this->headers->getDate('LastModified');
}
/**
* Sets the Last-Modified HTTP header with a \DateTime instance.
*
* If passed a null value, it deletes the header.
*
* @param \DateTime $date A \DateTime instance
*/
public function setLastModified(\DateTime $date = null)
{
if (null === $date)
{
$this->headers->delete('Last-Modified');
}
else
{
$this->headers->set('Last-Modified', $date->format(DATE_RFC2822));
}
}
/**
* Returns the literal value of ETag HTTP header.
*
* @return string The ETag HTTP header
*/
public function getEtag()
{
return $this->headers->get('ETag');
}
public function setEtag($etag = null)
{
if (null === $etag)
{
$this->headers->delete('Etag');
}
else
{
$this->headers->set('ETag', $etag);
}
}
/**
* Modifies the response so that it conforms to the rules defined for a 304 status code.
*
* This sets the status, removes the body, and discards any headers
* that MUST NOT be included in 304 responses.
*
* @see http://tools.ietf.org/html/rfc2616#section-10.3.5
*/
public function setNotModified()
{
$this->setStatusCode(304);
$this->setContent(null);
// remove headers that MUST NOT be included with 304 Not Modified responses
foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header)
{
$this->headers->delete($header);
}
}
/**
* Returns true if the response includes a Vary header.
*
* @return true if the response includes a Vary header, false otherwise
*/
public function hasVary()
{
return (Boolean) $this->headers->get('Vary');
}
/**
* Returns an array of header names given in the Vary header.
*
* @return array An array of Vary names
*/
public function getVary()
{
if (!$vary = $this->headers->get('Vary'))
{
return array();
}
return preg_split('/[\s,]+/', $vary);
}
/**
* Determines if the Response validators (ETag, Last-Modified) matches
* a conditional value specified in the Request.
*
* If the Response is not modified, it sets the status code to 304 and
* remove the actual content by calling the setNotModified() method.
*
* @param Request $request A Request instance
*
* @return Boolean true if the Response validators matches the Request, false otherwise
*/
public function isNotModified(Request $request)
{
$lastModified = $request->headers->get('If-Modified-Since');
$notModified = false;
if ($etags = $request->headers->get('If-None-Match'))
{
$etags = preg_split('/\s*,\s*/', $etags);
$notModified = (in_array($this->getEtag(), $etags) || in_array('*', $etags)) && (!$lastModified || $this->headers->get('Last-Modified') == $lastModified);
}
elseif ($lastModified)
{
$notModified = $lastModified == $this->headers->get('Last-Modified');
}
if ($notModified)
{
$this->setNotModified();
}
return $notModified;
}
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
public function isInvalid()
{
return $this->statusCode < 100 || $this->statusCode >= 600;
}
public function isInformational()
{
return $this->statusCode >= 100 && $this->statusCode < 200;
}
public function isSuccessful()
{
return $this->statusCode >= 200 && $this->statusCode < 300;
}
public function isRedirection()
{
return $this->statusCode >= 300 && $this->statusCode < 400;
}
public function isClientError()
{
return $this->statusCode >= 400 && $this->statusCode < 500;
}
public function isServerError()
{
return $this->statusCode >= 500 && $this->statusCode < 600;
}
public function isOk()
{
return 200 === $this->statusCode;
}
public function isForbidden()
{
return 403 === $this->statusCode;
}
public function isNotFound()
{
return 404 === $this->statusCode;
}
public function isRedirect()
{
return in_array($this->statusCode, array(301, 302, 303, 307));
}
public function isEmpty()
{
return in_array($this->statusCode, array(201, 204, 304));
}
}

View File

@ -0,0 +1,157 @@
<?php
/*
* This file is part of the symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Tests\Components\RequestHandler;
use Symfony\Components\RequestHandler\Response;
class ResponseTest extends \PHPUnit_Framework_TestCase
{
public function testIsValidateable()
{
$response = new Response('', 200, array('Last-Modified' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
$this->assertTrue($response->isValidateable(), '->isValidateable() returns true if Last-Modified is present');
$response = new Response('', 200, array('ETag' => '"12345"'));
$this->assertTrue($response->isValidateable(), '->isValidateable() returns true if ETag is present');
$response = new Response();
$this->assertFalse($response->isValidateable(), '->isValidateable() returns false when no validator is present');
}
public function testGetDate()
{
$response = new Response('', 200, array('Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
$this->assertEquals(0, $this->createDateTimeOneHourAgo()->diff($response->getDate())->format('%s'), '->getDate() returns the Date header if present');
$response = new Response();
$date = $response->getDate();
$this->assertLessThan(1, $date->diff(new \DateTime(), true)->format('%s'), '->getDate() returns the current Date if no Date header present');
$response = new Response('', 200, array('Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
$now = $this->createDateTimeNow();
$response->headers->set('Date', $now->format(DATE_RFC2822));
$this->assertEquals(0, $now->diff($response->getDate())->format('%s'), '->getDate() returns the date when the header has been modified');
}
public function getMaxAge()
{
$response = new Response();
$response->headers->set('Cache-Control', 's-maxage=600, max-age=0');
$this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() uses s-maxage cache control directive when present');
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=600');
$this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() falls back to max-age when no s-maxage directive present');
$response = new Response();
$response->headers->set('Cache-Control', 'must-revalidate');
$response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
$this->assertEquals(3600, $response->getMaxAge(), '->getMaxAge() falls back to Expires when no max-age or s-maxage directive present');
$response = new Response();
$this->assertNull($response->getMaxAge(), '->getMaxAge() returns null if no freshness information available');
}
public function testIsPrivate()
{
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=100');
$response->setPrivate(true);
$this->assertEquals(100, $response->headers->getCacheControl()->getMaxAge(), '->isPrivate() adds the private Cache-Control directive when set to true');
$this->assertTrue($response->headers->getCacheControl()->isPrivate(), '->isPrivate() adds the private Cache-Control directive when set to true');
$response = new Response();
$response->headers->set('Cache-Control', 'public, max-age=100');
$response->setPrivate(true);
$this->assertEquals(100, $response->headers->getCacheControl()->getMaxAge(), '->isPrivate() adds the private Cache-Control directive when set to true');
$this->assertTrue($response->headers->getCacheControl()->isPrivate(), '->isPrivate() adds the private Cache-Control directive when set to true');
$this->assertFalse($response->headers->getCacheControl()->isPublic(), '->isPrivate() removes the public Cache-Control directive');
}
public function testExpire()
{
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=100');
$response->expire();
$this->assertEquals(100, $response->headers->get('Age'), '->expire() sets the Age to max-age when present');
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=100, s-maxage=500');
$response->expire();
$this->assertEquals(500, $response->headers->get('Age'), '->expire() sets the Age to s-maxage when both max-age and s-maxage are present');
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=5, s-maxage=500');
$response->headers->set('Age', '1000');
$response->expire();
$this->assertEquals(1000, $response->headers->get('Age'), '->expire() does nothing when the response is already stale/expired');
$response = new Response();
$response->expire();
$this->assertFalse($response->headers->has('Age'), '->expire() does nothing when the response does not include freshness information');
}
public function testGetTtl()
{
$response = new Response();
$this->assertNull($response->getTtl(), '->getTtl() returns null when no Expires or Cache-Control headers are present');
$response = new Response();
$response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
$this->assertLessThan(1, 3600 - $response->getTtl(), '->getTtl() uses the Expires header when no max-age is present');
$response = new Response();
$response->headers->set('Expires', $this->createDateTimeOneHourAgo()->format(DATE_RFC2822));
$this->assertLessThan(0, $response->getTtl(), '->getTtl() returns negative values when Expires is in part');
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=60');
$this->assertLessThan(1, 60 - $response->getTtl(), '->getTtl() uses Cache-Control max-age when present');
}
public function testGetVary()
{
$response = new Response();
$this->assertEquals(array(), $response->getVary(), '->getVary() returns an empty array if no Vary header is present');
$response = new Response();
$response->headers->set('Vary', 'Accept-Language');
$this->assertEquals(array('Accept-Language'), $response->getVary(), '->getVary() parses a single header name value');
$response = new Response();
$response->headers->set('Vary', 'Accept-Language User-Agent X-Foo');
$this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by spaces');
$response = new Response();
$response->headers->set('Vary', 'Accept-Language,User-Agent, X-Foo');
$this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by commas');
}
protected function createDateTimeOneHourAgo()
{
$date = new \DateTime();
return $date->sub(new \DateInterval('PT1H'));
}
protected function createDateTimeOneHourLater()
{
$date = new \DateTime();
return $date->add(new \DateInterval('PT1H'));
}
protected function createDateTimeNow()
{
return new \DateTime();
}
}