Completed
Push — master ( 5c55d7...79e99a )
by Fèvre
28s queued 15s
created

WithCachedRows   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
dl 0
loc 44
rs 10
c 1
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A useCachedRows() 0 3 1
A cache() 0 16 3
1
<?php
2
3
namespace Xetaravel\Http\Livewire\Traits;
4
5
use InvalidArgumentException;
6
7
trait WithCachedRows
8
{
9
    /**
10
     * Whatever we use the cache or not.
11
     *
12
     * @var bool
13
     */
14
    protected $useCache = false;
15
16
    /**
17
     * Modify the option to use the cache.
18
     *
19
     * @return void
20
     */
21
    public function useCachedRows(): void
22
    {
23
        $this->useCache = true;
24
    }
25
26
    /**
27
     * Function to store and get back queries result from the cache.
28
     *
29
     * @param mixed $callback The callback function. (The query stored)
30
     *
31
     * @return mixed
32
     *
33
     * @throws InvalidArgumentException
34
     */
35
    public function cache($callback)
36
    {
37
        $cacheKey = $this->id;
38
39
        // If we use the cache and the cache has the id, return it.
40
        if ($this->useCache && cache()->has($cacheKey)) {
41
            return cache()->get($cacheKey);
42
        }
43
44
        // Get the callback result.
45
        $result = $callback();
46
47
        // Store the result in the cache.
48
        cache()->put($cacheKey, $result);
49
50
        return $result;
51
    }
52
}
53