Completed
Pull Request — master (#38)
by Jérôme
11:50
created

GreedyCacheStrategy   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 7
c 1
b 0
f 1
lcom 1
cbo 5
dl 0
loc 53
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getCacheKey() 0 6 1
A cache() 0 16 2
A getCacheObject() 0 9 2
A fetch() 0 4 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
        $response = $response->withAddedHeader(
43
            'Warning',
44
            'This response is cached although the response headers indicate not to do it!'
45
        );
46
47
        if ($cacheObject = $this->getCacheObject($request, $response)) {
48
            return $this->storage->save(
49
                $this->getCacheKey($request),
50
                $cacheObject
51
            );
52
        }
53
54
        return false;
55
    }
56
57
    protected function getCacheObject(RequestInterface $request, ResponseInterface $response)
58
    {
59
        if (!array_key_exists($response->getStatusCode(), $this->statusAccepted)) {
60
            // Don't cache it
61
            return null;
62
        }
63
64
        return new CacheEntry($request, $response, new \DateTime(sprintf('+%d seconds', $this->ttl)));
65
    }
66
67
    public function fetch(RequestInterface $request)
68
    {
69
        return $this->storage->fetch($this->getCacheKey($request));
70
    }
71
}
72