|
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
|
|
|
* @var callable|null Key generator |
|
33
|
|
|
*/ |
|
34
|
|
|
private $keyGeneratorCallback; |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* @param CacheItemPoolInterface $cachePool Cache pool |
|
38
|
|
|
* @param SourceAdapterInterface $adapter Inner adapter |
|
39
|
|
|
* @param callable $keyGeneratorCallback Key generator |
|
40
|
|
|
*/ |
|
41
|
|
|
public function __construct(CacheItemPoolInterface $cachePool, $adapter, $keyGeneratorCallback = null) |
|
42
|
|
|
{ |
|
43
|
|
|
$this->cachePool = $cachePool; |
|
44
|
|
|
$this->adapter = $adapter; |
|
45
|
|
|
$this->keyGeneratorCallback = $keyGeneratorCallback; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* {@inheritdoc} |
|
50
|
|
|
*/ |
|
51
|
|
|
public function receive(Request $request) |
|
52
|
|
|
{ |
|
53
|
|
|
if (is_callable($this->keyGeneratorCallback)) { |
|
54
|
|
|
$key = call_user_func_array($this->keyGeneratorCallback, array($request)); |
|
55
|
|
|
} else { |
|
56
|
|
|
$key = md5(serialize($request->getData())); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
$item = $this->cachePool->getItem($key); |
|
60
|
|
|
|
|
61
|
|
|
if (!$item->isHit()) { |
|
62
|
|
|
$response = $this->adapter->receive($request); |
|
63
|
|
|
|
|
64
|
|
|
$response->setHeader('cache-status', self::MISS); |
|
65
|
|
|
$response->setHeader('cache-key', $key); |
|
66
|
|
|
|
|
67
|
|
|
$item->set($response); |
|
68
|
|
|
|
|
69
|
|
|
$this->cachePool->save($item); |
|
70
|
|
|
|
|
71
|
|
|
return $response; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
/** @var Response $response */ |
|
75
|
|
|
$response = $item->get(); |
|
76
|
|
|
|
|
77
|
|
|
$response->setHeader('cache-status', self::HIT); |
|
78
|
|
|
$response->setHeader('cache-key', $key); |
|
79
|
|
|
$response->setHeader('cache-data', $response->getData()); |
|
80
|
|
|
|
|
81
|
|
|
return $response; |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|