Completed
Push — 2.2 ( 592af0...dcdea8 )
by Han Hui
16s queued 10s
created

CachedTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
dl 0
loc 36
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B getCached() 0 30 6
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[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 ApiPlatform\Core\Cache;
15
16
use Psr\Cache\CacheException;
17
use Psr\Cache\CacheItemPoolInterface;
18
19
/**
20
 * @internal
21
 */
22
trait CachedTrait
23
{
24
    /** @var CacheItemPoolInterface */
25
    private $cacheItemPool;
26
    private $localCache = [];
27
28
    private function getCached(string $cacheKey, callable $getValue)
29
    {
30
        if (array_key_exists($cacheKey, $this->localCache)) {
31
            return $this->localCache[$cacheKey];
32
        }
33
34
        try {
35
            $cacheItem = $this->cacheItemPool->getItem($cacheKey);
36
37
            if ($cacheItem->isHit()) {
38
                return $this->localCache[$cacheKey] = $cacheItem->get();
39
            }
40
        } catch (CacheException $e) {
41
            //do nothing
42
        }
43
44
        $value = $getValue();
45
46
        if (!isset($cacheItem)) {
47
            return $this->localCache[$cacheKey] = $value;
48
        }
49
50
        try {
51
            $cacheItem->set($value);
52
            $this->cacheItemPool->save($cacheItem);
53
        } catch (CacheException $e) {
54
            // do nothing
55
        }
56
57
        return $this->localCache[$cacheKey] = $value;
58
    }
59
}
60