Completed
Push — master ( 40aedc...7c1b35 )
by Nils
05:00
created

CacheDecorator::disableCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace whm\Smoke\Http;
4
5
use Cache\Adapter\Common\CacheItem;
6
use GuzzleHttp\Psr7\Request;
7
use Ivory\HttpAdapter\ConfigurationInterface;
8
use Ivory\HttpAdapter\HttpAdapterInterface;
9
use Psr\Cache\CacheItemPoolInterface;
10
use Psr\Http\Message\RequestInterface;
11
use whm\Smoke\Extensions\SmokeHttpClient\CacheAware;
12
13
class CacheDecorator implements HttpAdapterInterface, CacheAware
14
{
15
    private $client;
16
    private $cacheItemPool;
17
18
    private $disabled = false;
19
20
    public function __construct(HttpAdapterInterface $client, CacheItemPoolInterface $cacheItemPool)
21
    {
22
        $this->client = $client;
23
        $this->cacheItemPool = $cacheItemPool;
24
    }
25
26
    public function disableCache()
27
    {
28
        $this->disabled = true;
29
    }
30
31
    public function enableCache()
32
    {
33
        $this->disabled = false;
34
    }
35
36
    /**
37
     * Serialize a response so it can be stored inside a cache element.
38
     *
39
     * @param Response $response
40
     * @return string
41
     */
42
    private function serializeResponse(Response $response)
43
    {
44
        $array = ['object' => serialize($response), 'body' => (string)$response->getBody()];
45
        return serialize($array);
46
    }
47
48
    /**
49
     * Unserialze a response from cache element
50
     *
51
     * @param $serializedResponse
52
     * @return Response
53
     */
54
    private function unserializeResponse($serializedResponse)
55
    {
56
        $array = unserialize($serializedResponse);
57
58
        $response = unserialize($array['object']);
59
        /** @var Response $response */
60
        $response->setBody($array['body']);
61
62
        return $response;
63
    }
64
65
    private function getHash($uri, $headers)
66
    {
67
        return md5(json_encode((string)$uri) . json_encode($headers));
68
    }
69
70
    private function cacheResponse($key, Response $response)
71
    {
72
        $serializedResponse = $this->serializeResponse($response);
73
74
        $item = new CacheItem($key);
75
        $item->set($serializedResponse);
76
        $item->expiresAfter(new \DateInterval('P5M'));
77
78
        $this->cacheItemPool->save($item);
79
    }
80
81
    public function get($uri, array $headers = array())
82
    {
83
        if ($this->disabled) {
84
            return $this->client->get($uri, $headers);
85
        } else {
86
            $key = $this->getHash($uri, $headers);
87
88
            if ($this->cacheItemPool->hasItem($key)) {
89
                $serializedResponse = $this->cacheItemPool->getItem($key)->get();
90
                return $this->unserializeResponse($serializedResponse);
91
            } else {
92
                $response = $this->client->get($uri, $headers);
93
                /** @var Response $response */
94
                $this->cacheResponse($key, $response);
95
                return $response;
96
            }
97
        }
98
    }
99
100
    public function head($uri, array $headers = array())
101
    {
102
        return $this->client->head($uri, $headers);
103
    }
104
105
    public function trace($uri, array $headers = array())
106
    {
107
        return $this->client->trace($uri, $headers);
108
    }
109
110
    public function post($uri, array $headers = array(), $datas = array(), array $files = array())
111
    {
112
        var_dump('post');
0 ignored issues
show
Security Debugging Code introduced by
var_dump('post'); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
113
        return $this->client->post($uri, $headers, $datas, $files);
114
    }
115
116
    public function put($uri, array $headers = array(), $datas = array(), array $files = array())
117
    {
118
        return $this->client->put($uri, $headers, $datas, $files);
119
    }
120
121
    public function patch($uri, array $headers = array(), $datas = array(), array $files = array())
122
    {
123
        return $this->client->patch($uri, $headers, $datas, $files);
124
    }
125
126
    public function delete($uri, array $headers = array(), $datas = array(), array $files = array())
127
    {
128
        return $this->client->delete($uri, $headers, $datas, $files);
129
    }
130
131
    public function options($uri, array $headers = array(), $datas = array(), array $files = array())
132
    {
133
        return $this->client->options($uri, $headers, $datas, $files);
134
    }
135
136
    public function send($uri, $method, array $headers = array(), $datas = array(), array $files = array())
137
    {
138
        var_dump('send');
0 ignored issues
show
Security Debugging Code introduced by
var_dump('send'); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
139
        return $this->client->send($uri, $method, $headers, $datas, $files);
140
    }
141
142
    public function getConfiguration()
143
    {
144
        return $this->client->getConfiguration();
145
    }
146
147
    public function setConfiguration(ConfigurationInterface $configuration)
148
    {
149
        return $this->client->setConfiguration($configuration);
150
    }
151
152
    public function sendRequest(RequestInterface $request)
153
    {
154
        var_dump('sendRequest');
0 ignored issues
show
Security Debugging Code introduced by
var_dump('sendRequest'); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
155
        return $this->client->sendRequest($request);
156
    }
157
158
    /**
159
     * @param Request[] $requests
160
     * @return Response[]
161
     */
162
    public function sendRequests(array $requests)
163
    {
164
        if ($this->disabled) {
165
            return $this->client->sendRequests($requests);
166
        } else {
167
            $responses = array();
168
169
            foreach ($requests as $id => $request) {
170
                $key = $this->getHash($request->getUri(), $request->getHeaders());
171
                if ($this->cacheItemPool->hasItem($key)) {
172
                    $responses[] = $this->unserializeResponse($this->cacheItemPool->getItem($key)->get());
173
                    unset($requests[$id]);
174
                }
175
            }
176
177
            $newResponses = $this->client->sendRequests($requests);
178
179
            foreach ($newResponses as $newResponse) {
180
                /** @var Response $newResponse */
181
                $key = $this->getHash($newResponse->getRequest()->getUri(), $newResponse->getRequest()->getHeaders());
182
                $this->cacheResponse($key, $newResponse);
183
            }
184
185
            $responses = array_merge($responses, $newResponses);
186
187
            return $responses;
188
        }
189
    }
190
191
    public function getName()
192
    {
193
        return $this->client->getName();
194
    }
195
}