Passed
Push — 5.0.0 ( dd8bc0...b0cec2 )
by Fèvre
05:00
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
c 1
b 0
f 0
dl 0
loc 44
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A cache() 0 16 3
A useCachedRows() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Xetaravel\Livewire\Traits;
6
7
use InvalidArgumentException;
8
9
trait WithCachedRows
10
{
11
    /**
12
     * Whatever we use the cache or not.
13
     *
14
     * @var bool
15
     */
16
    protected bool $useCache = false;
17
18
    /**
19
     * Modify the option to use the cache.
20
     *
21
     * @return void
22
     */
23
    public function useCachedRows(): void
24
    {
25
        $this->useCache = true;
26
    }
27
28
    /**
29
     * Function to store and get back queries result from the cache.
30
     *
31
     * @param mixed $callback The callback function. (The query stored)
32
     *
33
     * @return mixed
34
     *
35
     * @throws InvalidArgumentException
36
     */
37
    public function cache(mixed $callback): mixed
38
    {
39
        $cacheKey = $this->getId();
0 ignored issues
show
Bug introduced by
It seems like getId() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

39
        /** @scrutinizer ignore-call */ 
40
        $cacheKey = $this->getId();
Loading history...
40
41
        // If we use the cache and the cache has the id, return it.
42
        if ($this->useCache && cache()->has($cacheKey)) {
43
            return cache()->get($cacheKey);
44
        }
45
46
        // Get the callback result.
47
        $result = $callback();
48
49
        // Store the result in the cache.
50
        cache()->put($cacheKey, $result);
51
52
        return $result;
53
    }
54
}
55