LazyCacheTrait::lazy()   B
last analyzed

Complexity

Conditions 5
Paths 10

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.2499

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 12
cts 19
cp 0.6316
rs 8.439
c 0
b 0
f 0
cc 5
eloc 15
nc 10
nop 4
crap 6.2499
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: bethrezen
5
 * Date: 28.09.15
6
 * Time: 16:05
7
 */
8
9
namespace DevGroup\TagDependencyHelper;
10
11
use yii\caching\TagDependency;
12
13
/**
14
 * LazyCacheTrait is used when you have your own implementation of \yii\caching\Cache and don't want to use as behavior.
15
 * Trait is a bit faster behavior.
16
 *
17
 * @package DevGroup\TagDependencyHelper
18
 */
19
trait LazyCacheTrait
20
{
21
    /**
22
     * Performs lazy caching. If $cacheKey is not found in cache - run callable and cache result.
23
     * Callable is called only if no cache entry
24
     *
25
     * @param callable                                $callable Callable to run for actual retrieving your info
26
     * @param string                                  $cacheKey Cache key string
27
     * @param int                                     $duration Duration of cache entry in seconds
28
     * @param null|\yii\caching\Dependency|string     $dependency Cache dependency
29
     *
30
     * @return mixed
31
     */
32 1
    public function lazy(callable $callable, $cacheKey, $duration = 86400, $dependency = null)
33
    {
34
        /** @var \yii\caching\Cache $owner */
35 1
        if (get_called_class() === LazyCache::className()) {
36 1
            $owner = $this->owner;
37 1
        } else {
38
            $owner = $this;
39
        }
40 1
        $result = $owner->get($cacheKey);
41 1
        if ($result === false) {
42 1
            $result = call_user_func($callable);
43
44 1
            if (is_string($dependency)) {
45
                $dependency = [$dependency];
46
            }
47 1
            if (is_array($dependency)) {
48
                $dependency = new TagDependency([
49
                    'tags' => $dependency,
50
                ]);
51
            }
52
53 1
            $owner->set($cacheKey, $result, $duration, $dependency);
54 1
        }
55 1
        return $result;
56
    }
57
}