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

CacheTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B getOrSave() 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
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