Passed
Push — master ( 1023c6...5cd462 )
by Stephen
04:15 queued 02:12
created

Cacheable   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 57
rs 10
wmc 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A fetch() 0 3 1
A invalidateCache() 0 5 1
A getTTL() 0 2 1
1
<?php
2
3
4
namespace Sfneal\Caching\Traits;
5
6
7
use Illuminate\Database\Eloquent\Collection;
8
use Illuminate\Support\Facades\Cache;
9
10
trait Cacheable
11
{
12
    /**
13
     * @var int Time to live
14
     */
15
    public $ttl = null;
16
17
    /**
18
     * Execute the Query
19
     *
20
     * @return Collection|int|mixed
21
     */
22
    abstract public function execute();
23
24
    /**
25
     * Retrieve the Query cache key
26
     *
27
     * @return string
28
     */
29
    abstract public function cacheKey(): string;
30
31
    /**
32
     * Fetch cached Query results
33
     *
34
     *  - use cacheKey() method to retrieve correct key to use for storing in cache
35
     *  - use base class's execute() method for retrieving query results
36
     *
37
     * @param int|null $ttl
38
     * @return Collection|mixed
39
     */
40
    public function fetch(int $ttl = null) {
41
        return Cache::remember($this->cacheKey(), $this->getTTL($ttl), function () {
42
            return $this->execute();
43
        });
44
    }
45
46
    /**
47
     * Retrieve the time to live for the cached values
48
     *  - 1. passed $ttl parameter
49
     *  - 2. initialized $this->ttl property
50
     *  - 3. application default cache ttl
51
     *
52
     * @param int|null $ttl
53
     * @return int|mixed
54
     */
55
    private function getTTL(int $ttl = null) {
56
        return $ttl ?? $this->ttl ?? env('REDIS_KEY_EXPIRATION');
57
    }
58
59
    /**
60
     * Invalidate the Query Cache for this Query
61
     */
62
    public function invalidateCache() {
63
        // todo: refactor to protected method
64
        // Remove # ID's from cache key
65
        redisDelete(collect(explode('#', $this->cacheKey(), 1))->first());
66
        return $this;
67
    }
68
}
69