Completed
Push — master ( 59bdcf...77f39a )
by Iman
02:18
created

Cache   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 76
rs 10
c 2
b 0
f 0
wmc 12
lcom 0
cbo 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B cacheResult() 0 22 6
B _makeCacheKey() 0 25 5
A cacheDriverSupportsTags() 0 4 1
1
<?php
2
3
namespace Imanghafoori\Widgets\Utils;
4
5
class Cache
6
{
7
    /**
8
     * Caches the widget output.
9
     *
10
     * @param $args
11
     * @param $phpCode
12
     * @param $widget
13
     *
14
     * @return null
15
     */
16
    public function cacheResult($args, $phpCode, $widget)
17
    {
18
        $key = $this->_makeCacheKey($args, $widget);
19
20
        $cache = app('cache');
21
22
        if ( !empty($widget->cacheTags) && $this->cacheDriverSupportsTags() ) {
23
            $cache = $cache->tags($widget->cacheTags);
24
        }
25
26
        if ($widget->cacheLifeTime > 0) {
27
            return $cache->remember($key, $widget->cacheLifeTime, $phpCode);
28
        }
29
30
        if ($widget->cacheLifeTime < 0) {
31
            return $cache->rememberForever($key, $phpCode);
32
        }
33
34
        if ($widget->cacheLifeTime === 0) {
35
            return $phpCode();
36
        }
37
    }
38
39
    /**
40
     * Creates a unique cache key for each possible output.
41
     *
42
     * @param $arg
43
     * @param $widget
44
     *
45
     * @return string
46
     */
47
    private function _makeCacheKey($arg, $widget)
48
    {
49
        if (method_exists($widget, 'cacheKey')) {
50
51
            return $widget->cacheKey();
52
        }
53
54
        $_key = '';
55
56
        if (method_exists($widget, 'extraCacheKeyDependency')) {
57
            $_key = json_encode($widget->extraCacheKeyDependency());
58
        }
59
60
61
        if(!$this->cacheDriverSupportsTags()){
62
            $_cache = app('cache');
63
            foreach ($widget->cacheTags as $tag){
64
                $_key .= $_cache->get($tag);
65
            }
66
        }
67
68
        $_key .= json_encode($arg, JSON_FORCE_OBJECT) . app()->getLocale() . $widget->template . get_class($widget);
69
70
        return md5($_key);
71
    }
72
73
    /**
74
     * @return bool
75
     */
76
    private function cacheDriverSupportsTags()
77
    {
78
        return ! in_array(env('CACHE_DRIVER', 'file'), ['file', 'database']);
79
    }
80
}
81