LazyCacheTrait   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 63.16%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 2
dl 0
loc 39
ccs 12
cts 19
cp 0.6316
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B lazy() 0 25 5
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
}