CacheHelper   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 3
eloc 7
c 3
b 0
f 1
dl 0
loc 38
ccs 7
cts 7
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A fetch() 0 11 3
1
<?php
2
3
namespace Vectorface\Cache;
4
5
use DateInterval;
6
7
/**
8
 * Class with a few methods that may assist in implementing item caching.
9
 */
10
class CacheHelper
11
{
12
    /**
13
     * Implement the mechanics of caching the result of a heavy function call.
14
     *
15
     * For example, if one has a function like so:
16
     * public static function getLargeDatasetFromDB($arg1, $arg2) {
17
     *     // Lots of SQL/compute
18
     *     return $giantDataSet;
19
     * }
20
     *
21
     * One could cache this by adding cache calls to the top/bottom. CacheHelper::fetch can automate this:
22
     *
23
     * function getLargeDataset($arg1, $arg2) {
24
     *     $key = "SomeClass::LargeDataset($arg1,$arg2)";
25
     *     $cache = new APCCache();
26
     *     return CacheHelper::fetch($cache, $key, [SomeClass, 'getLargeDatasetFromDB'], [$arg1, $arg2], 600);
27
     * }
28
     *
29
     * @param Cache $cache The cache from/to which the values should be retrieved/set.
30
     * @param string $key The cache key which should store the value.
31
     * @param callable $callback A callable which is expected to return a value to be cached.
32
     * @param mixed[] $args The arguments to be passed to the callback, if it needs to be called.
33
     * @param DateInterval|int|null $ttl If a value is to be set in the cache, set this expiry time (in seconds).
34
     * @return mixed The value stored in the cache, or returned by the callback.
35 1
     * @throws Exception\CacheException
36
     */
37 1
    public static function fetch(Cache $cache, string $key, callable $callback, array $args = [], DateInterval|int|null $ttl = 300) : mixed
38 1
    {
39 1
        $item = $cache->get($key);
40
        if ($item === null) {
41 1
            $item = $callback(...$args);
42 1
43
            if (isset($item)) {
44
                $cache->set($key, $item, $ttl);
45 1
            }
46
        }
47
        return $item;
48
    }
49
}
50