CacheMiddleware   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 10

Test Coverage

Coverage 89.47%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
dl 0
loc 41
rs 10
c 2
b 1
f 0
ccs 17
cts 19
cp 0.8947
wmc 4
lcom 0
cbo 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B handle() 0 32 4
1
<?php
2
/**
3
 * @author    jan huang <[email protected]>
4
 * @copyright 2016
5
 *
6
 * @see      https://www.github.com/janhuang
7
 * @see      https://fastdlabs.com
8
 */
9
10
namespace FastD\Middleware;
11
12
use FastD\Http\Response;
13
use FastD\Utils\DateObject;
14
use Psr\Http\Message\ResponseInterface;
15
use Psr\Http\Message\ServerRequestInterface;
16
17
/**
18
 * Class CacheMiddleware.
19
 */
20
class CacheMiddleware extends Middleware
21
{
22
    /**
23
     * @param ServerRequestInterface $request
24
     * @param DelegateInterface      $next
25
     *
26
     * @return ResponseInterface
27
     */
28 7
    public function handle(ServerRequestInterface $request, DelegateInterface $next)
29
    {
30 7
        if ('GET' !== $request->getMethod()) {
31
            return $next->process($request);
32
        }
33
34 7
        $key = md5($request->getUri()->getPath().http_build_query($request->getQueryParams()));
35 7
        $cache = cache()->getItem($key);
36 7
        if ($cache->isHit()) {
37 6
            list($content, $headers) = $cache->get();
38
39 6
            return new Response($content, Response::HTTP_OK, $headers);
40
        }
41
42 1
        $response = $next->process($request);
43 1
        if (Response::HTTP_OK !== $response->getStatusCode()) {
44
            return $response;
45
        }
46
47 1
        $expireAt = DateObject::createFromTimestamp(time() + config()->get('common.cache.lifetime', 60));
48
49 1
        $response->withHeader('X-Cache', $key)->withExpires($expireAt);
50
51 1
        $cache->set([
52 1
            (string) $response->getBody(),
53 1
            $response->getHeaders(),
54 1
        ]);
55
56 1
        cache()->save($cache->expiresAt($expireAt));
57
58 1
        return $response;
59
    }
60
}
61