Passed
Push — develop ( 641127...4c2f3c )
by Jonathan
01:36
created

CacheHelper::runCallback()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.1406

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 3
c 1
b 0
f 1
dl 0
loc 6
ccs 3
cts 4
cp 0.75
rs 10
cc 3
nc 3
nop 2
crap 3.1406
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 = static::runCallback($callback, $args);
39
40 1
            if (isset($item)) {
41 1
                $cache->set($key, $item, $ttl);
42
            }
43
        }
44 1
        return $item;
45
    }
46
47
    /**
48
     * Run the callback, normalizing the arguments.
49
     *
50
     * @param callable $callback The callable to be executed to fetch the value the cache.
51
     * @param mixed[] $args The argument(s) to the callback function.
52
     * @return mixed The value returned by the callback.
53
     */
54 1
    protected static function runCallback($callback, $args)
55
    {
56 1
        if (!is_array($args)) {
0 ignored issues
show
introduced by
The condition is_array($args) is always true.
Loading history...
57
            $args = isset($args) ? [$args] : [];
58
        }
59 1
        return call_user_func_array($callback, $args);
60
    }
61
}
62