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

QueryCacher::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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