Passed
Pull Request — 2.2 (#1908)
by Ben
03:10
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 3
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