Test Failed
Push — master ( a81572...90f7a4 )
by Daniel
04:32
created

CachedTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
A getCached() 0 22 4
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentsBundle\Cache;
15
16
use Psr\Cache\CacheException;
17
use Psr\Cache\CacheItemPoolInterface;
18
19
/**
20
 * @description Copied from API Platform implementation - no author specified in file
21
 *
22
 * @internal
23
 */
24
trait CachedTrait
25
{
26
    private CacheItemPoolInterface $cacheItemPool;
27
    private array $localCache = [];
28
29
    private function getCached(string $cacheKey, callable $getValue)
30
    {
31
        if (\array_key_exists($cacheKey, $this->localCache)) {
32
            return $this->localCache[$cacheKey];
33
        }
34
35
        try {
36
            $cacheItem = $this->cacheItemPool->getItem($cacheKey);
37
        } catch (CacheException $e) {
38
            return $this->localCache[$cacheKey] = $getValue();
39
        }
40
41
        if ($cacheItem->isHit()) {
42
            return $this->localCache[$cacheKey] = $cacheItem->get();
43
        }
44
45
        $value = $getValue();
46
47
        $cacheItem->set($value);
48
        $this->cacheItemPool->save($cacheItem);
49
50
        return $this->localCache[$cacheKey] = $value;
51
    }
52
}
53