1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace NilPortugues\MessageBus\QueryBus; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
use NilPortugues\MessageBus\QueryBus\Contracts\Query; |
7
|
|
|
use NilPortugues\MessageBus\QueryBus\Contracts\QueryBusMiddleware as QueryBusMiddlewareInterface; |
8
|
|
|
use NilPortugues\MessageBus\QueryBus\Contracts\QueryResponse; |
9
|
|
|
use NilPortugues\MessageBus\Serializer\Contracts\Serializer; |
10
|
|
|
use Psr\Cache\CacheItemPoolInterface; |
11
|
|
|
|
12
|
|
|
class CacheQueryBusMiddleware implements QueryBusMiddlewareInterface |
13
|
|
|
{ |
14
|
|
|
/** @var CacheItemPoolInterface */ |
15
|
|
|
protected $cache; |
16
|
|
|
|
17
|
|
|
/** @var Serializer */ |
18
|
|
|
protected $serializer; |
19
|
|
|
|
20
|
|
|
/** @var int */ |
21
|
|
|
protected $ttl; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* CachingQueryBus constructor. |
25
|
|
|
* |
26
|
|
|
* @param Serializer $serializer |
27
|
|
|
* @param CacheItemPoolInterface $cacheItemPool |
28
|
|
|
* @param int $expirationInSeconds |
29
|
|
|
*/ |
30
|
|
|
public function __construct( |
31
|
|
|
Serializer $serializer, |
32
|
|
|
CacheItemPoolInterface $cacheItemPool, |
33
|
|
|
int $expirationInSeconds |
34
|
|
|
) { |
35
|
|
|
$this->cache = $cacheItemPool; |
36
|
|
|
$this->serializer = $serializer; |
37
|
|
|
$this->ttl = $expirationInSeconds; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param Query $query |
42
|
|
|
* @param callable|null $next |
43
|
|
|
* |
44
|
|
|
* @return QueryResponse |
45
|
|
|
*/ |
46
|
|
|
public function __invoke(Query $query, callable $next = null) : QueryResponse |
47
|
|
|
{ |
48
|
|
|
if (null === $next) { |
49
|
|
|
throw new InvalidArgumentException('callable $next must not be null.'); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$cache = $this->cache->getItem($this->queryHashing($query)); |
53
|
|
|
|
54
|
|
|
if ($cache->isHit()) { |
55
|
|
|
return $this->serializer->unserialize($cache->get()); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$response = $next($query); |
59
|
|
|
|
60
|
|
|
$cache->set($this->serializer->serialize($response)); |
61
|
|
|
$cache->expiresAfter($this->ttl); |
62
|
|
|
$this->cache->save($cache); |
63
|
|
|
|
64
|
|
|
return $response; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param Query $query |
69
|
|
|
* |
70
|
|
|
* @return string |
71
|
|
|
*/ |
72
|
|
|
protected function queryHashing(Query $query) : string |
73
|
|
|
{ |
74
|
|
|
return md5(serialize($query)); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|