Completed
Pull Request — master (#38)
by Jérôme
12:36 queued 11:57
created

GreedyCacheStrategy::getCacheKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Kevinrob\GuzzleCache\Strategy;
4
5
use Kevinrob\GuzzleCache\CacheEntry;
6
use Kevinrob\GuzzleCache\Storage\CacheStorageInterface;
7
use Psr\Http\Message\RequestInterface;
8
use Psr\Http\Message\ResponseInterface;
9
10
/**
11
 * This strategy represent a "greedy" HTTP client.
12
 *
13
 * It can be used to cache responses in spite of any cache related response headers,
14
 * but it SHOULDN'T be used unless absolutely necessary, e.g. when accessing
15
 * badly designed APIs without Cache control.
16
 *
17
 * Obviously, this follows no RFC :(.
18
 */
19
class GreedyCacheStrategy extends PrivateCacheStrategy
20
{
21
    /**
22
     * @var int
23
     */
24
    protected $ttl;
25
26
    public function __construct(CacheStorageInterface $cache = null, $ttl)
27
    {
28
        $this->ttl = $ttl;
29
30
        parent::__construct($cache);
31
    }
32
33
    protected function getCacheKey(RequestInterface $request)
34
    {
35
        return sha1(
36
            'greedy'.$request->getMethod().$request->getUri()
37
        );
38
    }
39
40
    public function cache(RequestInterface $request, ResponseInterface $response)
41
    {
42
        if ($cacheObject = $this->getCacheObject($request, $response)) {
43
            return $this->storage->save(
44
                $this->getCacheKey($request),
45
                $cacheObject
46
            );
47
        }
48
49
        return false;
50
    }
51
52
    protected function getCacheObject(RequestInterface $request, ResponseInterface $response)
53
    {
54
        if (!array_key_exists($response->getStatusCode(), $this->statusAccepted)) {
55
            // Don't cache it
56
            return null;
57
        }
58
59
        return new CacheEntry($request, $response, new \DateTime(sprintf('+%d seconds', $this->ttl)));
60
    }
61
62
    public function fetch(RequestInterface $request)
63
    {
64
        return $this->storage->fetch($this->getCacheKey($request));
65
    }
66
}
67