Completed
Pull Request — master (#16)
by Yuichi
09:45 queued 07:37
created

CacheStorage::getCacheKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
rs 9.4285
cc 1
eloc 6
nc 1
nop 1
1
<?php
2
3
namespace CybozuHttp\Subscriber\Cache;
4
5
use GuzzleHttp\Message\RequestInterface;
6
use GuzzleHttp\Message\ResponseInterface;
7
use GuzzleHttp\Message\Response;
8
use GuzzleHttp\Stream;
9
use Doctrine\Common\Cache\Cache;
10
11
/**
12
 * @author ochi51 <[email protected]>
13
 */
14
class CacheStorage
15
{
16
    /** @var int Default cache TTL */
17
    private $defaultTtl;
18
19
    /** @var Cache */
20
    private $cache;
21
22
    /**
23
     * @param Cache  $cache     Cache backend.
24
     * @param int    $defaultTtl
25
     */
26
    public function __construct(Cache $cache, $defaultTtl = 0)
27
    {
28
        $this->cache = $cache;
29
        $this->defaultTtl = $defaultTtl;
30
    }
31
32
    public function cache(RequestInterface $request, ResponseInterface $response)
33
    {
34
        $ttl = $this->defaultTtl;
35
        $key = $this->getCacheKey($request);
36
37
        // Persist the response body if needed
38
        if ($response->getStatusCode() === 200
39
            && $response->getBody()
40
            && $response->getBody()->getSize() > 0) {
41
            $this->cache->save($key, (string)$response->getBody(), $ttl);
42
        }
43
    }
44
45
    public function delete(RequestInterface $request)
46
    {
47
        $key = $this->getCacheKey($request);
48
        $this->cache->delete($key);
49
    }
50
51
    public function fetch(RequestInterface $request)
52
    {
53
        $key = $this->getCacheKey($request);
54
        if (!($body = $this->cache->fetch($key))) {
55
            return false;
56
        }
57
58
        $response = new Response(200);
59
        $response->setBody(Stream\Utils::create($body));
60
61
        return $response;
62
    }
63
64
    /**
65
     * Hash a request URL into a string that returns cache metadata
66
     *
67
     * @param RequestInterface $request
68
     *
69
     * @return string
70
     */
71
    private function getCacheKey(RequestInterface $request)
72
    {
73
        return $request->getMethod()
74
        . ' '
75
        . $request->getUrl()
76
        . ' '
77
        . (string)$request->getBody();
78
    }
79
}