Skip to content

Commit

Permalink
Merge pull request #32 from adriansuter/patch-slim4
Browse files Browse the repository at this point in the history
Add Slim 4 support
  • Loading branch information
l0gicgate authored Jun 18, 2020
2 parents 9b9e6c6 + e7228fb commit ab0b9fc
Show file tree
Hide file tree
Showing 13 changed files with 425 additions and 191 deletions.
14 changes: 14 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Enforce Unix newlines
* text=lf

# Exclude unused files
# see: https://redd.it/2jzp6k
/tests export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/.travis.yml export-ignore
/CONTRIBUTING.md export-ignore
/phpcs.xml.dist export-ignore
/phpstan.neon.dist export-ignore
/phpunit.xml.dist export-ignore
/README.md export-ignore
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
vendor
/.idea
/coverage
/vendor
.phpunit.result.cache
composer.lock
29 changes: 22 additions & 7 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
language: php

php:
- 5.5
- 5.6
- 7.0
- 7.1
dist: trusty

before_script: composer install
matrix:
include:
- php: 7.2
- php: 7.3
- php: 7.4
env: ANALYSIS='true'
- php: nightly
allow_failures:
- php: nightly

script: phpunit --coverage-text
before_script:
- if [[ "$ANALYSIS" == 'true' ]]; then composer require php-coveralls/php-coveralls:^2.1.0 ; fi
- composer install -n

script:
- if [[ "$ANALYSIS" != 'true' ]]; then vendor/bin/phpunit ; fi
- if [[ "$ANALYSIS" == 'true' ]]; then vendor/bin/phpunit --coverage-clover clover.xml ; fi
- if [[ "$ANALYSIS" == 'true' ]]; then vendor/bin/phpcs ; fi
- if [[ "$ANALYSIS" == 'true' ]]; then vendor/bin/phpstan analyse src ; fi

after_success:
- if [[ "$ANALYSIS" == 'true' ]]; then vendor/bin/php-coveralls --coverage_clover=clover.xml -v ; fi
38 changes: 24 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Slim Framework HTTP Cache

[![Build Status](https://travis-ci.org/slimphp/Slim-HttpCache.svg?branch=master)](https://travis-ci.org/slimphp/Slim-HttpCache)
[![Latest Stable Version](https://poser.pugx.org/slim/http-cache/v)](//packagist.org/packages/slim/http-cache)
[![License](https://poser.pugx.org/slim/http-cache/license)](https://packagist.org/packages/slim/http-cache)

This repository contains a Slim Framework HTTP cache middleware and service provider.

Expand All @@ -12,30 +14,38 @@ Via Composer
$ composer require slim/http-cache
```

Requires Slim 3.0.0 or newer.
Requires Slim 4.0.0 or newer.

## Usage

```php
$app = new \Slim\App();
declare(strict_types=1);

// Register middleware
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

require __DIR__.'/../vendor/autoload.php';

$app = \Slim\Factory\AppFactory::create();

// Register the http cache middleware.
$app->add(new \Slim\HttpCache\Cache('public', 86400));

// Fetch DI Container
$container = $app->getContainer();
// Create the cache provider.
$cacheProvider = new \Slim\HttpCache\CacheProvider();

// Register service provider
$container['cache'] = function () {
return new \Slim\HttpCache\CacheProvider();
};
// Register a route and let the closure callback inherit the cache provider.
$app->get(
'/',
function (Request $request, Response $response, array $args) use ($cacheProvider): Response {
// Use the cache provider.
$response = $cacheProvider->withEtag($response, 'abc');

// Example route with ETag header
$app->get('/foo', function ($req, $res, $args) {
$resWithEtag = $this->cache->withEtag($res, 'abc');
$response->getBody()->write('Hello world!');

return $resWithEtag;
});
return $response;
}
);

$app->run();
```
Expand Down
78 changes: 48 additions & 30 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,33 +1,51 @@
{
"name": "slim/http-cache",
"type": "library",
"description": "Slim Framework HTTP cache middleware and service provider",
"keywords": ["slim","framework","middleware","cache"],
"homepage": "http://slimframework.com",
"license": "MIT",
"authors": [
{
"name": "Josh Lockhart",
"email": "[email protected]",
"homepage": "http://joshlockhart.com"
}
],
"require": {
"php": ">=5.5.0",
"psr/http-message": "^1.0"
},
"require-dev": {
"slim/slim": "^3.0",
"phpunit/phpunit": "^4.0"
},
"autoload": {
"psr-4": {
"Slim\\HttpCache\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Slim\\HttpCache\\Tests\\": "tests"
}
"name": "slim/http-cache",
"type": "library",
"description": "Slim Framework HTTP cache middleware and service provider",
"keywords": [
"slim",
"framework",
"middleware",
"cache"
],
"homepage": "https://www.slimframework.com",
"license": "MIT",
"authors": [
{
"name": "Josh Lockhart",
"email": "[email protected]",
"homepage": "http://joshlockhart.com"
}
],
"require": {
"php": "^7.2",
"psr/http-message": "^1.0",
"psr/http-server-middleware": "^1.0"
},
"require-dev": {
"slim/psr7": "^1.1",
"phpunit/phpunit": "^8.5",
"squizlabs/php_codesniffer": "^3.5",
"phpstan/phpstan": "^0.12.28"
},
"autoload": {
"psr-4": {
"Slim\\HttpCache\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Slim\\HttpCache\\Tests\\": "tests"
}
},
"scripts": {
"test": [
"@phpcs",
"@phpstan",
"@phpunit"
],
"phpcs": "phpcs",
"phpstan": "phpstan analyse src --memory-limit=-1",
"phpunit": "phpunit"
}
}
17 changes: 17 additions & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0"?>
<ruleset name="Slim coding standard">
<description>Slim coding standard</description>

<!-- display progress -->
<arg value="p"/>
<!-- use colors in output -->
<arg name="colors"/>

<!-- inherit rules from: -->
<rule ref="PSR2"/>
<rule ref="Generic.Arrays.DisallowLongArraySyntax"/>

<!-- Paths to check -->
<file>src</file>
<file>tests</file>
</ruleset>
3 changes: 3 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
parameters:
level: max
inferPrivatePropertyTypeFromConstructor: true
26 changes: 18 additions & 8 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,25 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/8.5/phpunit.xsd"
backupGlobals="false"
backupStaticAttributes="false"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutChangesToGlobalState="true"
beStrictAboutOutputDuringTests="true"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="tests/bootstrap.php"
>
<testsuites>
<testsuite name="Slim Test Suite">
<directory>tests/</directory>
<testsuite name="Slim HttpCache Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>

<filter>
<whitelist>
<directory>src/</directory>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory>./src/</directory>
</whitelist>
</filter>
<logging>
<log
type="coverage-html"
target="./coverage"
lowUpperBound="20"
highLowerBound="50"
/>
</logging>
</phpunit>
71 changes: 45 additions & 26 deletions src/Cache.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,28 @@
<?php
/**
* Slim Framework (https://www.slimframework.com)
*
* @license https://github.com/slimphp/Slim-HttpCache/blob/master/LICENSE.md (MIT License)
*/

declare(strict_types=1);

namespace Slim\HttpCache;

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

class Cache
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

use function in_array;
use function is_array;
use function is_numeric;
use function preg_split;
use function reset;
use function sprintf;
use function strtotime;

class Cache implements MiddlewareInterface
{
/**
* Cache-Control type (public or private)
Expand Down Expand Up @@ -34,44 +52,45 @@ class Cache
* @param int $maxAge The maximum age of client-side cache
* @param bool $mustRevalidate must-revalidate
*/
public function __construct($type = 'private', $maxAge = 86400, $mustRevalidate = false)
public function __construct(string $type = 'private', int $maxAge = 86400, bool $mustRevalidate = false)
{
$this->type = $type;
$this->maxAge = $maxAge;
$this->mustRevalidate = $mustRevalidate;
}

/**
* Invoke cache middleware
*
* @param RequestInterface $request A PSR7 request object
* @param ResponseInterface $response A PSR7 response object
* @param callable $next The next middleware callable
*
* @return ResponseInterface A PSR7 response object
* {@inheritDoc}
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $next($request, $response);
$response = $handler->handle($request);

// Cache-Control header
if (!$response->hasHeader('Cache-Control')) {
if ($this->maxAge === 0) {
$response = $response->withHeader('Cache-Control', sprintf(
'%s, no-cache%s',
$this->type,
$this->mustRevalidate ? ', must-revalidate' : ''
));
$response = $response->withHeader(
'Cache-Control',
sprintf(
'%s, no-cache%s',
$this->type,
$this->mustRevalidate ? ', must-revalidate' : ''
)
);
} else {
$response = $response->withHeader('Cache-Control', sprintf(
'%s, max-age=%s%s',
$this->type,
$this->maxAge,
$this->mustRevalidate ? ', must-revalidate' : ''
));
$response = $response->withHeader(
'Cache-Control',
sprintf(
'%s, max-age=%s%s',
$this->type,
$this->maxAge,
$this->mustRevalidate ? ', must-revalidate' : ''
)
);
}
}


// ETag header and conditional GET check
$etag = $response->getHeader('ETag');
$etag = reset($etag);
Expand All @@ -81,7 +100,7 @@ public function __invoke(RequestInterface $request, ResponseInterface $response,

if ($ifNoneMatch) {
$etagList = preg_split('@\s*,\s*@', $ifNoneMatch);
if (in_array($etag, $etagList) || in_array('*', $etagList)) {
if (is_array($etagList) && (in_array($etag, $etagList) || in_array('*', $etagList))) {
return $response->withStatus(304);
}
}
Expand All @@ -92,7 +111,7 @@ public function __invoke(RequestInterface $request, ResponseInterface $response,
$lastModified = $response->getHeaderLine('Last-Modified');

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

Expand Down
Loading

0 comments on commit ab0b9fc

Please sign in to comment.