HttpCacheMiddleware   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 30
rs 10
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A process() 0 20 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chinstrap\Core\Http\Middleware;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
12
final class HttpCacheMiddleware implements MiddlewareInterface
13
{
14
    /**
15
     * @var array
16
     */
17
    private array $cacheableStatus = [
18
                                200,
19
                                304,
20
                               ];
21
22
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
23
    {
24
        $response = $handler->handle($request);
25
        $env = $request->getServerParams();
26
        if ($env['APP_ENV'] === 'development') {
27
            return $response;
28
        }
29
30
        if ($request->getMethod() !== 'GET' || !in_array($response->getStatusCode(), $this->cacheableStatus)) {
31
            return $response;
32
        }
33
34
        $maxLifetime = isset($env['CACHE_TIME']) ? (int)$env['CACHE_TIME'] : 3600; // cache for 1 hour
35
36
        return $response->withAddedHeader(
37
            'Cache-Control',
38
            "public, max-age=$maxLifetime"
39
        )->withAddedHeader(
40
            'Expires',
41
            gmdate("D, d M Y H:i:s", time() + $maxLifetime) . " GMT"
42
        );
43
    }
44
}
45