Passed
Push — master ( fe19bd...35c88b )
by Mike
02:28
created

ModelCaching::scopeDisableCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php namespace GeneaLabs\LaravelModelCaching\Traits;
2
3
use GeneaLabs\LaravelModelCaching\CachedBuilder;
4
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
5
6
trait ModelCaching
7
{
8
    public static function all($columns = ['*'])
9
    {
10
        if (config('laravel-model-caching.disabled')) {
11
            return parent::all($columns);
12
        }
13
14
        $class = get_called_class();
15
        $instance = new $class;
16
        $tags = [str_slug(get_called_class())];
17
        $key = $instance->makeCacheKey();
18
19
        return $instance->cache($tags)
20
            ->rememberForever($key, function () use ($columns) {
21
                return parent::all($columns);
22
            });
23
    }
24
25
    public static function bootCachable()
26
    {
27
        static::saved(function ($instance) {
28
            $instance->checkCooldownAndFlushAfterPersiting($instance);
29
        });
30
31
        static::pivotAttached(function ($instance) {
32
            $instance->checkCooldownAndFlushAfterPersiting($instance);
33
        });
34
35
        static::pivotDetached(function ($instance) {
36
            $instance->checkCooldownAndFlushAfterPersiting($instance);
37
        });
38
39
        static::pivotUpdated(function ($instance) {
40
            $instance->checkCooldownAndFlushAfterPersiting($instance);
41
        });
42
    }
43
44
    public function newEloquentBuilder($query)
45
    {
46
        if (! $this->isCachable()) {
47
            $this->isCachable = true;
48
49
            return new EloquentBuilder($query);
50
        }
51
52
        return new CachedBuilder($query);
53
    }
54
55
    public function scopeDisableCache(EloquentBuilder $query) : EloquentBuilder
56
    {
57
        $query = $query->disableModelCaching();
58
59
        return $query;
60
    }
61
62
    public function scopeWithCacheCooldownSeconds(
63
        EloquentBuilder $query,
64
        int $seconds
65
    ) : EloquentBuilder {
66
        $cachePrefix = $this->getCachePrefix();
67
        $modelClassName = get_class($this);
68
        $cacheKey = "{$cachePrefix}:{$modelClassName}-cooldown:seconds";
69
70
        $this->cache()
71
            ->rememberForever($cacheKey, function () use ($seconds) {
72
                return $seconds;
73
            });
74
75
        $cacheKey = "{$cachePrefix}:{$modelClassName}-cooldown:invalidated-at";
76
        $this->cache()
77
            ->rememberForever($cacheKey, function () {
78
                return now();
79
            });
80
81
        return $query;
82
    }
83
}
84