Passed
Pull Request — master (#1908)
by Ben
02:54
created

CacheTrait::getOrSave()   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 4
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
trait CacheTrait
20
{
21
    public function getOrSave(string $cacheKey, CacheItemPoolInterface $pool, &$localCache, callable $callback)
22
    {
23
        if (isset($localCache[$cacheKey])) {
24
            return $localCache[$cacheKey];
25
        }
26
27
        try {
28
            $cacheItem = $pool->getItem($cacheKey);
29
30
            if ($cacheItem->isHit()) {
31
                return $localCache[$cacheKey] = $cacheItem->get();
32
            }
33
        } catch (CacheException $e) {
34
            //do nothing
35
        }
36
37
        $routeName = $callback();
38
39
        if (!isset($cacheItem)) {
40
            return $localCache[$cacheKey] = $routeName;
41
        }
42
43
        try {
44
            $cacheItem->set($routeName);
45
            $pool->save($cacheItem);
46
        } catch (CacheException $e) {
47
            // do nothing
48
        }
49
50
        return $localCache[$cacheKey] = $routeName;
51
    }
52
}
53