Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Separate cache relevant methods #11

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 12 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,25 @@ Requires Slim 3.0.0 or newer.
```php
$app = new \Slim\App();

// Register middleware
$app->add(new \Slim\HttpCache\Cache('public', 86400));
// Register middleware to automatically set default cache headers
$app->add(new \Slim\Middleware\HttpCache\Cache('public', 86400));

// Fetch DI Container
$container = $app->getContainer();

// Register service provider
$container->register(new \Slim\HttpCache\CacheProvider);
// Register service provider to get access to the cache methods
$container->register(new \Slim\Middleware\HttpCache\CacheProvider);

// Example route with ETag header
$app->get('/foo', function ($req, $res, $args) {
$resWithEtag = $this['cache']->withEtag($res, 'abc');
$resWithEtag = $this->cache->withEtag($res, 'abc');

// Optional: Return early if the Etag matches the Etag in the request
if ($this->cache->isStillValid($req, $resWithEtag)) {
return $resWithEtag->withStatus(304);
}

$resWithEtag->getBody()->write('foo');

return $resWithEtag;
});
Expand Down
9 changes: 2 additions & 7 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,11 @@
"psr/http-message": "^1.0"
},
"require-dev": {
"slim/slim": "dev-develop"
"slim/slim": "^3.0@dev"
},
"autoload": {
"psr-4": {
"Slim\\HttpCache\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Slim\\HttpCache\\Tests\\": "tests"
"Slim\\Middleware\\HttpCache\\": "src"
}
}
}
64 changes: 23 additions & 41 deletions src/Cache.php
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
<?php
namespace Slim\HttpCache;
namespace Slim\Middleware\HttpCache;

use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class Cache
{
/**
* Cache-Control type (public or private)
* @var CacheHelper
*/
protected $cache;

/**
* Default Cache-Control type (public or private)
*
* @var string
*/
protected $type;

/**
* Cache-Control max age in seconds
* Default Cache-Control max age in seconds
*
* @var int
*/
Expand All @@ -25,13 +28,15 @@ class Cache
/**
* Create new HTTP cache
*
* @param string $type The cache type: "public" or "private"
* @param int $maxAge The maximum age of client-side cache
* @param string $type The cache type: "public" or "private"
* @param int $maxAge The maximum age of client-side cache
* @param CacheHelper $cache The cache object to use

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$cache can also be null:

@param CacheHelper|null $cache The cache object to use.

*/
public function __construct($type = 'private', $maxAge = 86400)
public function __construct($type = 'private', $maxAge = 86400, CacheHelper $cache = null)
{
$this->type = $type;
$this->maxAge = $maxAge;
$this->cache = $cache ?: new CacheHelper();
}

/**
Expand All @@ -45,45 +50,22 @@ public function __construct($type = 'private', $maxAge = 86400)
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
/** @var ResponseInterface $response */
$response = $next($request, $response);

// Cache-Control header
if (!$response->hasHeader('Cache-Control')) {
$response = $response->withHeader('Cache-Control', sprintf(
'%s, max-age=%s',
$this->type,
$this->maxAge
));
// Don't add cache headers if the request method is not safe
if (!in_array($request->getMethod(), ['GET', 'HEAD'])) {
return $response;
}

// Last-Modified header and conditional GET check
$lastModified = $response->getHeaderLine('Last-Modified');

if ($lastModified) {
if (!is_integer($lastModified)) {
$lastModified = strtotime($lastModified);
}

$ifModifiedSince = $request->getHeaderLine('If-Modified-Since');

if ($ifModifiedSince && $lastModified <= strtotime($ifModifiedSince)) {
return $response->withStatus(304);
}
// Automatically add the default Cache-Control header
if (!$response->hasHeader('Cache-Control')) {
$response = $this->cache->allowCache($response, $this->type, $this->maxAge);
}

// ETag header and conditional GET check
$etag = $response->getHeader('ETag');
$etag = reset($etag);

if ($etag) {
$ifNoneMatch = $request->getHeaderLine('If-None-Match');

if ($ifNoneMatch) {
$etagList = preg_split('@\s*,\s*@', $ifNoneMatch);
if (in_array($etag, $etagList) || in_array('*', $etagList)) {
return $response->withStatus(304);
}
}
// Check if the client cache is still valid
if ($response->getStatusCode() !== 304 && $this->cache->isStillValid($request, $response)) {
return $response->withStatus(304);
}

return $response;
Expand Down
153 changes: 153 additions & 0 deletions src/CacheHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
<?php
namespace Slim\Middleware\HttpCache;

use InvalidArgumentException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class CacheHelper
{
/**
* Enable client-side HTTP caching
*
* @param ResponseInterface $response PSR7 response object
* @param string $type Cache-Control type: "private" or "public"
* @param null|int|string $maxAge Maximum cache age (integer timestamp or datetime string)
*
* @return ResponseInterface A new PSR7 response object with `Cache-Control` header
* @throws InvalidArgumentException if the cache-control type is invalid
*/
public function allowCache(ResponseInterface $response, $type = 'private', $maxAge = null)
{
if (!in_array($type, ['private', 'public'])) {
throw new InvalidArgumentException('Invalid Cache-Control type. Must be "public" or "private".');
}
$headerValue = $type;
if ($maxAge) {
if (!is_integer($maxAge)) {
$maxAge = strtotime($maxAge);
}
$headerValue = $headerValue . ', max-age=' . $maxAge;
}

return $response->withHeader('Cache-Control', $headerValue);
}

/**
* Disable client-side HTTP caching
*
* @param ResponseInterface $response PSR7 response object
*
* @return ResponseInterface A new PSR7 response object with `Cache-Control` header
*/
public function denyCache(ResponseInterface $response)
{
return $response->withHeader('Cache-Control', 'no-store,no-cache');
}

/**
* Add `Expires` header to PSR7 response object
*
* @param ResponseInterface $response A PSR7 response object
* @param int|string $time A UNIX timestamp or a valid `strtotime()` string
*
* @return ResponseInterface A new PSR7 response object with `Expires` header
* @throws InvalidArgumentException if the expiration date cannot be parsed
*/
public function withExpires(ResponseInterface $response, $time)
{
if (!is_integer($time)) {
$time = strtotime($time);
if ($time === false) {
throw new InvalidArgumentException('Expiration value could not be parsed with `strtotime()`.');
}
}

return $response->withHeader('Expires', gmdate('D, d M Y H:i:s T', $time));
}

/**
* Add `ETag` header to PSR7 response object
*
* @param ResponseInterface $response A PSR7 response object
* @param string $value The ETag value
* @param string $type ETag type: "strong" or "weak"
*
* @return ResponseInterface A new PSR7 response object with `ETag` header
* @throws InvalidArgumentException if the etag type is invalid
*/
public function withEtag(ResponseInterface $response, $value, $type = 'strong')
{
if (!in_array($type, ['strong', 'weak'])) {
throw new InvalidArgumentException('Invalid etag type. Must be "strong" or "weak".');
}
$value = '"' . $value . '"';
if ($type === 'weak') {
$value = 'W/' . $value;
}

return $response->withHeader('ETag', $value);
}

/**
* Add `Last-Modified` header to PSR7 response object
*
* @param ResponseInterface $response A PSR7 response object
* @param int|string $time A UNIX timestamp or a valid `strtotime()` string
*
* @return ResponseInterface A new PSR7 response object with `Last-Modified` header
* @throws InvalidArgumentException if the last modified date cannot be parsed
*/
public function withLastModified(ResponseInterface $response, $time)
{
if (!is_integer($time)) {
$time = strtotime($time);
if ($time === false) {
throw new InvalidArgumentException('Last Modified value could not be parsed with `strtotime()`.');
}
}

return $response->withHeader('Last-Modified', gmdate('D, d M Y H:i:s T', $time));
}

/**
* Compares the request and the response to determine if the client still has a valid copy.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @return bool
*/
public function isStillValid(RequestInterface $request, ResponseInterface $response)
{
// Last-Modified header and conditional GET check
$lastModified = $response->getHeaderLine('Last-Modified');

if ($lastModified) {
if (!is_integer($lastModified)) {
$lastModified = strtotime($lastModified);
}

$ifModifiedSince = $request->getHeaderLine('If-Modified-Since');

if ($ifModifiedSince && $lastModified <= strtotime($ifModifiedSince)) {
return true;
}
}

// ETag header and conditional GET check
$etag = $response->getHeaderLine('ETag');

if ($etag) {
$ifNoneMatch = $request->getHeaderLine('If-None-Match');

if ($ifNoneMatch) {
$etagList = preg_split('@\s*,\s*@', $ifNoneMatch);
if (in_array(str_replace('"', '', $etag), $etagList) || in_array('*', $etagList)) {
return true;
}
}
}

return false;
}
}