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
|
|
|
|