|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Sludio\HelperBundle\Guzzle\GuzzleHttp\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use GuzzleHttp\Promise\FulfilledPromise; |
|
6
|
|
|
use Psr\Http\Message\RequestInterface; |
|
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
8
|
|
|
use Sludio\HelperBundle\Guzzle\Cache\StorageAdapterInterface; |
|
9
|
|
|
|
|
10
|
|
|
class CacheMiddleware |
|
11
|
|
|
{ |
|
12
|
|
|
const DEBUG_HEADER = 'X-Guzzle-Cache'; |
|
13
|
|
|
const DEBUG_HEADER_HIT = 'HIT'; |
|
14
|
|
|
const DEBUG_HEADER_MISS = 'MISS'; |
|
15
|
|
|
|
|
16
|
|
|
protected $adapter; |
|
17
|
|
|
protected $debug; |
|
18
|
|
|
|
|
19
|
|
|
public function __construct(StorageAdapterInterface $adapter, $debug = false) |
|
20
|
|
|
{ |
|
21
|
|
|
$this->adapter = $adapter; |
|
22
|
|
|
$this->debug = $debug; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public function __invoke(callable $handler) |
|
26
|
|
|
{ |
|
27
|
|
|
return function(RequestInterface $request, array $options) use ($handler) { |
|
28
|
|
|
if (!$response = $this->adapter->fetch($request)) { |
|
29
|
|
|
return $this->handleSave($handler, $request, $options); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
$response = $this->addDebugHeader($response, static::DEBUG_HEADER_HIT); |
|
33
|
|
|
|
|
34
|
|
|
return new FulfilledPromise($response); |
|
35
|
|
|
}; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
protected function handleSave(callable $handler, RequestInterface $request, array $options) |
|
39
|
|
|
{ |
|
40
|
|
|
return $handler($request, $options)->then(function(ResponseInterface $response) use ($request) { |
|
41
|
|
|
$code = (int)floor((int)$response->getStatusCode() / 100); |
|
42
|
|
|
if ($code === 2) { |
|
43
|
|
|
$this->adapter->save($request, $response); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
return $this->addDebugHeader($response, static::DEBUG_HEADER_MISS); |
|
47
|
|
|
}); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
protected function addDebugHeader(ResponseInterface $response, $value) |
|
51
|
|
|
{ |
|
52
|
|
|
if (!$this->debug) { |
|
53
|
|
|
return $response; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
return $response->withHeader(static::DEBUG_HEADER, $value); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|