Passed
Push — master ( 159f4a...679316 )
by
unknown
02:11
created

CacheHelper::runCallback()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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