Passed
Pull Request — 2.2 (#1908)
by Ben
03:10
created

CacheTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
dl 0
loc 34
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
    private $localCache = [];
22
23
    private function getOrSave(string $cacheKey, CacheItemPoolInterface $pool, callable $callback)
24
    {
25
        if (isset($this->localCache[$cacheKey])) {
26
            return $this->localCache[$cacheKey];
27
        }
28
29
        try {
30
            $cacheItem = $pool->getItem($cacheKey);
31
32
            if ($cacheItem->isHit()) {
33
                return $this->localCache[$cacheKey] = $cacheItem->get();
34
            }
35
        } catch (CacheException $e) {
36
            //do nothing
37
        }
38
39
        $routeName = $callback();
40
41
        if (!isset($cacheItem)) {
42
            return $this->localCache[$cacheKey] = $routeName;
43
        }
44
45
        try {
46
            $cacheItem->set($routeName);
47
            $pool->save($cacheItem);
48
        } catch (CacheException $e) {
49
            // do nothing
50
        }
51
52
        return $this->localCache[$cacheKey] = $routeName;
53
    }
54
}
55