Test Setup Failed
Push — master ( 1007a9...600158 )
by Christian
08:04
created

QueryCacher   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 29
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A __invoke() 0 17 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RemotelyLiving\PHPQueryBus\Middleware;
6
7
use Psr\Cache\CacheItemPoolInterface;
8
use RemotelyLiving\PHPQueryBus\Interfaces\CacheableQuery;
9
use RemotelyLiving\PHPQueryBus\Interfaces\Query;
10
use RemotelyLiving\PHPQueryBus\Interfaces\Result;
11
12
final class QueryCacher
13
{
14
    /**
15
     * @var \Psr\Cache\CacheItemPoolInterface
16
     */
17
    private $cachePool;
18
19
    public function __construct(CacheItemPoolInterface $cachePool)
20
    {
21
        $this->cachePool = $cachePool;
22
    }
23
24
    public function __invoke(Query $query, callable $next): Result
25
    {
26
        if (!$query instanceof CacheableQuery) {
27
            return $next($query);
28
        }
29
30
        $cachedResult = $this->cachePool->getItem($query->getCacheKey());
31
        if ($cachedResult->isHit()) {
32
            return $cachedResult->get();
33
        }
34
35
        $cachedResult->set($next($query))
36
            ->expiresAfter($query->getTTL());
37
38
        $this->cachePool->save($cachedResult);
39
40
        return $cachedResult->get();
41
    }
42
}
43