1 | <?php |
||
5 | class Cache |
||
6 | { |
||
7 | private $_cacheTag; |
||
8 | |||
9 | /** |
||
10 | * Cache constructor. |
||
11 | */ |
||
12 | public function __construct() |
||
16 | |||
17 | /** |
||
18 | * Caches the widget output. |
||
19 | * |
||
20 | * @param array $args |
||
21 | * @param callable $phpCode |
||
22 | * @param object $widgetObj |
||
23 | * |
||
24 | * @param string $form |
||
25 | * @return null |
||
26 | */ |
||
27 | public function cacheResult(array $args, callable $phpCode, $widgetObj, $form = 'HTML') |
||
28 | { |
||
29 | $key = $this->makeCacheKey($args, $widgetObj, $form); |
||
30 | |||
31 | $cache = app('cache'); |
||
32 | |||
33 | if (! empty($widgetObj->cacheTags) && $this->cacheDriverSupportsTags()) { |
||
34 | $cache = $cache->tags($widgetObj->cacheTags); |
||
35 | } |
||
36 | |||
37 | if ($widgetObj->cacheLifeTime === 0) { |
||
38 | return $phpCode(); |
||
39 | } |
||
40 | |||
41 | return $cache->remember($key, $widgetObj->cacheLifeTime, $phpCode); |
||
42 | } |
||
43 | |||
44 | /** |
||
45 | * Creates a unique cache key for each possible output. |
||
46 | * |
||
47 | * @param array $arg |
||
48 | * @param object $widget |
||
49 | * @param string $form |
||
50 | * @return string An MD5 string |
||
51 | */ |
||
52 | private function makeCacheKey(array $arg, $widget, $form) |
||
53 | { |
||
54 | if (method_exists($widget, 'cacheKey')) { |
||
55 | return $widget->cacheKey($arg); |
||
56 | } |
||
57 | |||
58 | $_key = ''; |
||
59 | |||
60 | if (method_exists($widget, 'extraCacheKeyDependency')) { |
||
61 | $_key = json_encode($widget->extraCacheKeyDependency($arg)); |
||
62 | } |
||
63 | |||
64 | if (! $this->cacheDriverSupportsTags()) { |
||
65 | $_key .= json_encode($this->getTagTokens($widget->cacheTags)); |
||
66 | } |
||
67 | |||
68 | $_key .= json_encode($arg, JSON_FORCE_OBJECT).app()->getLocale().$form.$widget->template.get_class($widget); |
||
69 | |||
70 | return md5($_key); |
||
71 | } |
||
72 | |||
73 | /** |
||
74 | * Determines cacheTagging is supported by the chosen laravel cache driver or not. |
||
75 | * @return bool |
||
76 | */ |
||
77 | private function cacheDriverSupportsTags() |
||
78 | { |
||
79 | return ! in_array(config('cache.default', 'file'), ['file', 'database']); |
||
80 | } |
||
81 | |||
82 | /** |
||
83 | * @param string[] $cacheTags |
||
84 | * @return string[] |
||
85 | */ |
||
86 | private function getTagTokens(array $cacheTags) |
||
92 | |||
93 | /** |
||
94 | * @param string[] $tags |
||
95 | */ |
||
96 | public function expireTaggedWidgets($tags) |
||
110 | } |
||
111 |