Passed
Pull Request — master (#83)
by BENOIT
02:37
created

GreedyCacheStrategy::getCacheKey()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 16
cts 16
cp 1
rs 8.7624
c 0
b 0
f 0
cc 5
eloc 12
nc 4
nop 2
crap 5
1
<?php
2
3
namespace Kevinrob\GuzzleCache\Strategy;
4
5
use Kevinrob\GuzzleCache\CacheEntry;
6
use Kevinrob\GuzzleCache\KeyValueHttpHeader;
7
use Kevinrob\GuzzleCache\Storage\CacheStorageInterface;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
11
/**
12
 * This strategy represents a "greedy" HTTP client.
13
 *
14
 * It can be used to cache responses in spite of any cache related response headers,
15
 * but it SHOULDN'T be used unless absolutely necessary, e.g. when accessing
16
 * badly designed APIs without Cache control.
17
 *
18
 * Obviously, this follows no RFC :(.
19
 */
20
class GreedyCacheStrategy extends PrivateCacheStrategy
21
{
22
    /**
23
     * @var int
24
     */
25
    protected $ttl;
26
27
    /**
28
     * @var KeyValueHttpHeader
29
     */
30
    private $varyHeaders;
31
32 7
    public function __construct(CacheStorageInterface $cache = null, $ttl, KeyValueHttpHeader $varyHeaders = null)
33
    {
34 7
        $this->ttl = $ttl;
35 7
        $this->varyHeaders = $varyHeaders;
36 7
        parent::__construct($cache);
37 7
    }
38
39 6
    protected function getCacheKey(RequestInterface $request, KeyValueHttpHeader $varyHeaders = null)
40
    {
41 6
        if (null === $varyHeaders || $varyHeaders->isEmpty()) {
42 5
            return hash(
43 5
                'sha256',
44 5
                'greedy'.$request->getMethod().$request->getUri()
45 5
            );
46
        }
47
48 1
        $cacheHeaders = [];
49 1
        foreach ($varyHeaders as $key => $value) {
50 1
            if ($request->hasHeader($key)) {
51 1
                $cacheHeaders[$key] = $request->getHeader($key);
52 1
            }
53 1
        }
54
55 1
        return hash(
56 1
            'sha256',
57 1
            'greedy'.$request->getMethod().$request->getUri().json_encode($cacheHeaders)
58 1
        );
59
    }
60
61 6
    public function cache(RequestInterface $request, ResponseInterface $response)
62
    {
63 6
        $warningMessage = sprintf('%d - "%s" "%s"',
64 6
            299,
65 6
            'Cached although the response headers indicate not to do it!',
66 6
            (new \DateTime())->format(\DateTime::RFC1123)
67 6
        );
68
69 6
        $response = $response->withAddedHeader('Warning', $warningMessage);
70
71 6
        if ($cacheObject = $this->getCacheObject($request, $response)) {
72 5
            return $this->storage->save(
73 5
                $this->getCacheKey($request, $this->varyHeaders),
74
                $cacheObject
75 5
            );
76
        }
77
78 1
        return false;
79
    }
80
81 6
    protected function getCacheObject(RequestInterface $request, ResponseInterface $response)
82
    {
83 6
        if (!array_key_exists($response->getStatusCode(), $this->statusAccepted)) {
84
            // Don't cache it
85 1
            return null;
86
        }
87
88 5
        if (null !== $this->varyHeaders && $this->varyHeaders->has('*')) {
89
            // This will never match with a request
90
            return;
91
        }
92
93
94 5
        return new CacheEntry($request, $response, new \DateTime(sprintf('+%d seconds', $this->ttl)));
95
    }
96
97 6
    public function fetch(RequestInterface $request)
98
    {
99 6
        $cache = $this->storage->fetch($this->getCacheKey($request, $this->varyHeaders));
100 6
        return $cache;
101
    }
102
}
103