1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace EmanueleMinotto\GuzzleSnapshot\Strategy; |
6
|
|
|
|
7
|
|
|
use Doctrine\Common\Cache\Cache; |
8
|
|
|
use GuzzleHttp\Promise\FulfilledPromise; |
9
|
|
|
use GuzzleHttp\Promise\PromiseInterface; |
10
|
|
|
use function GuzzleHttp\Psr7\parse_response; |
11
|
|
|
use function GuzzleHttp\Psr7\str; |
12
|
|
|
use Psr\Http\Message\RequestInterface; |
13
|
|
|
use Psr\Http\Message\ResponseInterface; |
14
|
|
|
use Throwable; |
15
|
|
|
|
16
|
|
|
class DoctrineCacheStrategy implements StrategyInterface |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var Cache |
20
|
|
|
*/ |
21
|
|
|
private $cache; |
22
|
|
|
|
23
|
12 |
|
public function __construct(Cache $cache) |
24
|
|
|
{ |
25
|
12 |
|
$this->cache = $cache; |
26
|
12 |
|
} |
27
|
|
|
|
28
|
6 |
|
public function getPromise(RequestInterface $request): ?PromiseInterface |
29
|
|
|
{ |
30
|
6 |
|
$id = sha1(str($request)); |
31
|
|
|
|
32
|
6 |
|
if (!$this->cache->contains($id.'-response')) { |
33
|
3 |
|
return null; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
try { |
37
|
3 |
|
return new FulfilledPromise( |
38
|
3 |
|
parse_response($this->cache->fetch($id.'-response')) |
39
|
|
|
); |
40
|
|
|
} catch (Throwable $exception) { |
41
|
|
|
return null; |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
3 |
|
public function storeRequest(RequestInterface $request): void |
46
|
|
|
{ |
47
|
3 |
|
$this->storeContent($request, 'request', str($request)); |
48
|
3 |
|
} |
49
|
|
|
|
50
|
3 |
|
public function storeResponse(RequestInterface $request, ResponseInterface $response): void |
51
|
|
|
{ |
52
|
3 |
|
$this->storeContent($request, 'response', str($response)); |
53
|
3 |
|
} |
54
|
|
|
|
55
|
6 |
|
private function storeContent(RequestInterface $request, string $type, string $content): void |
56
|
|
|
{ |
57
|
6 |
|
$id = sha1(str($request)); |
58
|
|
|
|
59
|
6 |
|
$this->cache->save($id.'-'.$type, $content); |
60
|
6 |
|
} |
61
|
|
|
} |
62
|
|
|
|