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
![]() |
|||
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 | $cacheKey = md5($cacheKey); |
||
47 | $data = null; |
||
48 | $cacheItem = $this->getCacheAdapter()->getItem($cacheKey); |
||
49 | if ($cacheItem && $cacheItem->isHit()) { |
||
50 | $data = $cacheItem->get(); |
||
51 | } else { |
||
52 | $data = $closure(); |
||
53 | if ($data && $cacheItem) { |
||
54 | $cacheItem->set($data); |
||
55 | if (!empty($tags)) { |
||
56 | $cacheItem->tag($tags); |
||
57 | } |
||
58 | if ($expiresAfter) { |
||
0 ignored issues
–
show
|
|||
59 | $cacheItem->expiresAfter($expiresAfter); |
||
60 | } |
||
61 | $this->getCacheAdapter()->save($cacheItem); |
||
62 | } |
||
63 | } |
||
64 | |||
65 | return $data; |
||
66 | } |
||
67 | |||
68 | /** |
||
69 | * @param string $cacheKey |
||
70 | * @throws \Psr\Cache\InvalidArgumentException |
||
71 | */ |
||
72 | public function removeByKey(string $cacheKey): void |
||
73 | { |
||
74 | if (empty($cacheKey)) { |
||
75 | $cacheKey = md5($cacheKey); |
||
76 | $this->getCacheAdapter()->delete($cacheKey); |
||
77 | } |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * @param array $tags |
||
82 | */ |
||
83 | public function removeByTag(array $tags): void |
||
84 | { |
||
85 | $this->getCacheAdapter()->invalidateTags($tags); |
||
86 | } |
||
87 | } |
||
88 |