Passed
Push — master ( 617266...2422af )
by Siim
10:33
created

CacheAdapterTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 52
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setCacheAdapter() 0 3 1
A getCacheAdapter() 0 3 1
A getCacheDataOrAdd() 0 21 5
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: siim
5
 * Date: 21.02.19
6
 * Time: 20:22
7
 */
8
9
namespace Sf4\Api\RequestHandler\Traits;
10
11
use Sf4\Api\Services\CacheAdapterInterface;
12
13
trait CacheAdapterTrait
14
{
15
16
    /** @var CacheAdapterInterface $cacheAdapter */
17
    protected $cacheAdapter;
18
19
    /**
20
     * @return CacheAdapterInterface
21
     */
22
    public function getCacheAdapter(): CacheAdapterInterface
23
    {
24
        return $this->cacheAdapter;
25
    }
26
27
    /**
28
     * @param CacheAdapterInterface $cacheAdapter
29
     */
30
    public function setCacheAdapter(CacheAdapterInterface $cacheAdapter): void
31
    {
32
        $this->cacheAdapter = $cacheAdapter;
33
    }
34
35
    /**
36
     * @param string $cacheKey
37
     * @param \Closure $closure
38
     * @param array $tags
39
     * @param null $expiresAfter
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $expiresAfter is correct as it would always require null to be passed?
Loading history...
40
     * @return mixed|null
41
     * @throws \Psr\Cache\CacheException
42
     * @throws \Psr\Cache\InvalidArgumentException
43
     */
44
    public function getCacheDataOrAdd(string $cacheKey, \Closure $closure, array $tags = [], $expiresAfter = null)
45
    {
46
        $data = null;
47
        $cacheItem = $this->getCacheAdapter()->getItem($cacheKey);
48
        if ($cacheItem->isHit()) {
49
            $data = $cacheItem->get();
50
        } else {
51
            $data = $closure();
52
            if ($data) {
53
                $cacheItem->set($data);
54
                if (!empty($tags)) {
55
                    $cacheItem->tag($tags);
56
                }
57
                if ($expiresAfter) {
0 ignored issues
show
introduced by
$expiresAfter is of type null, thus it always evaluated to false.
Loading history...
58
                    $cacheItem->expiresAfter($expiresAfter);
59
                }
60
                $this->getCacheAdapter()->save($cacheItem);
61
            }
62
        }
63
64
        return $data;
65
    }
66
}
67