Test Failed
Pull Request — master (#67)
by
unknown
05:53
created

CacheMiddleware::handle()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 11.8736

Importance

Changes 6
Bugs 4 Features 0
Metric Value
cc 4
eloc 18
nc 4
nop 2
dl 0
loc 32
rs 8.5806
c 6
b 4
f 0
ccs 4
cts 19
cp 0.2105
crap 11.8736
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 8
    public function handle(ServerRequestInterface $request, DelegateInterface $next)
29
    {
30 8
        if ('GET' !== $request->getMethod()) {
31
            return $next->process($request);
32
        }
33
34 8
        $key = md5($request->getUri()->getPath().http_build_query($request->getQueryParams()));
35 8
        $cache = cache()->getItem($key);
36
        if ($cache->isHit()) {
37
            list($content, $headers) = $cache->get();
38
39
            return new Response($content, Response::HTTP_OK, $headers);
40
        }
41
42
        $response = $next->process($request);
43
        if (Response::HTTP_OK !== $response->getStatusCode()) {
44
            return $response;
45
        }
46
47
        $expireAt = DateObject::createFromTimestamp(time() + config()->get('common.cache.lifetime', 60));
48
49
        $response->withHeader('X-Cache', $key)->withExpires($expireAt);
50
51
        $cache->set([
52
            (string) $response->getBody(),
53
            $response->getHeaders(),
54
        ]);
55
56
        cache()->save($cache->expiresAt($expireAt));
57
58
        return $response;
59
    }
60
}
61