Completed
Push — master ( d4cfd0...1c3910 )
by Antoine
18s queued 10s
created

CachedTrait::getCached()   B

Complexity

Conditions 6
Paths 18

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.439
c 0
b 0
f 0
cc 6
eloc 15
nc 18
nop 2
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