1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sludio\HelperBundle\Guzzle\GuzzleHttp\Middleware; |
4
|
|
|
|
5
|
|
|
use Sludio\HelperBundle\Guzzle\Cache\StorageAdapterInterface; |
6
|
|
|
use GuzzleHttp\Promise\FulfilledPromise; |
7
|
|
|
use Psr\Http\Message\RequestInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
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
|
|
|
$this->adapter->save($request, $response); |
42
|
|
|
|
43
|
|
|
return $this->addDebugHeader($response, static::DEBUG_HEADER_MISS); |
44
|
|
|
}); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
protected function addDebugHeader(ResponseInterface $response, $value) |
48
|
|
|
{ |
49
|
|
|
if (!$this->debug) { |
50
|
|
|
return $response; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
return $response->withHeader(static::DEBUG_HEADER, $value); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|