|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of Transfer. |
|
5
|
|
|
* |
|
6
|
|
|
* For the full copyright and license information, please view the LICENSE file located |
|
7
|
|
|
* in the root directory. |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace Transfer\Adapter; |
|
11
|
|
|
|
|
12
|
|
|
use Psr\Cache\CacheItemPoolInterface; |
|
13
|
|
|
use Transfer\Adapter\Transaction\Request; |
|
14
|
|
|
use Transfer\Adapter\Transaction\Response; |
|
15
|
|
|
|
|
16
|
|
|
class CacheAdapter implements SourceAdapterInterface |
|
17
|
|
|
{ |
|
18
|
|
|
const HIT = 1; |
|
19
|
|
|
const MISS = 0; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var CacheItemPoolInterface Cache pool |
|
23
|
|
|
*/ |
|
24
|
|
|
private $cachePool; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @var SourceAdapterInterface Inner adapter |
|
28
|
|
|
*/ |
|
29
|
|
|
private $adapter; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @param CacheItemPoolInterface $cachePool Cache pool |
|
33
|
|
|
* @param SourceAdapterInterface $adapter Inner adapter |
|
34
|
|
|
*/ |
|
35
|
|
|
public function __construct(CacheItemPoolInterface $cachePool, $adapter) |
|
36
|
|
|
{ |
|
37
|
|
|
$this->cachePool = $cachePool; |
|
38
|
|
|
$this->adapter = $adapter; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* {@inheritdoc} |
|
43
|
|
|
*/ |
|
44
|
|
|
public function receive(Request $request) |
|
45
|
|
|
{ |
|
46
|
|
|
$id = md5(serialize($request->getData())); |
|
47
|
|
|
|
|
48
|
|
|
$item = $this->cachePool->getItem($id); |
|
49
|
|
|
|
|
50
|
|
|
if (!$item->isHit()) { |
|
51
|
|
|
$response = $this->adapter->receive($request); |
|
52
|
|
|
|
|
53
|
|
|
$response->setHeader('cache-status', self::MISS); |
|
54
|
|
|
$response->setHeader('cache-id', $id); |
|
55
|
|
|
|
|
56
|
|
|
$item->set($response); |
|
57
|
|
|
$this->cachePool->save($item); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** @var Response $response */ |
|
61
|
|
|
$response = $item->get(); |
|
62
|
|
|
|
|
63
|
|
|
$response->setHeader('cache-status', self::HIT); |
|
64
|
|
|
$response->setHeader('cache-id', $id); |
|
65
|
|
|
$response->setHeader('cache-data', $response->getData()); |
|
66
|
|
|
|
|
67
|
|
|
return $response; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|