Passed
Push — master ( 2eaef0...875cc9 )
by Mike
02:21
created

ModelCaching::__set()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 4
nop 2
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php namespace GeneaLabs\LaravelModelCaching\Traits;
2
3
use Carbon\Carbon;
4
use GeneaLabs\LaravelModelCaching\CachedBelongsToMany;
5
use GeneaLabs\LaravelModelCaching\CachedBuilder;
6
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
9
10
trait ModelCaching
11
{
12
    public function __get($key)
13
    {
14
        if ($key === "cachePrefix") {
15
            return $this->cachePrefix
16
                ?? "";
17
        }
18
19
        if ($key === "cacheCooldownSeconds") {
20
            return $this->cacheCooldownSeconds
21
                ?? 0;
22
        }
23
24
        return parent::__get($key);
25
    }
26
27
    public function __set($key, $value)
28
    {
29
        if ($key === "cachePrefix") {
30
            $this->cachePrefix = $value;
1 ignored issue
show
Bug Best Practice introduced by
The property cachePrefix does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
31
        }
32
33
        if ($key === "cacheCooldownSeconds") {
34
            $this->cacheCooldownSeconds = $value;
1 ignored issue
show
Bug Best Practice introduced by
The property cacheCooldownSeconds does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
35
        }
36
37
        parent::__set($key, $value);
38
    }
39
40
    public static function all($columns = ['*'])
41
    {
42
        if (config('laravel-model-caching.disabled')) {
43
            return parent::all($columns);
44
        }
45
46
        $class = get_called_class();
47
        $instance = new $class;
48
        $tags = $instance->makeCacheTags();
49
        $key = $instance->makeCacheKey();
50
51
        return $instance->cache($tags)
52
            ->rememberForever($key, function () use ($columns) {
53
                return parent::all($columns);
54
            });
55
    }
56
57
    public static function bootCachable()
58
    {
59
        static::created(function ($instance) {
60
            $instance->checkCooldownAndFlushAfterPersisting($instance);
61
        });
62
63
        static::deleted(function ($instance) {
64
            $instance->checkCooldownAndFlushAfterPersisting($instance);
65
        });
66
67
        static::saved(function ($instance) {
68
            $instance->checkCooldownAndFlushAfterPersisting($instance);
69
        });
70
71
        // TODO: figure out how to add this listener
72
        // static::restored(function ($instance) {
73
        //     $instance->checkCooldownAndFlushAfterPersisting($instance);
74
        // });
75
76
        static::pivotAttached(function ($instance, $secondInstance, $relationship) {
77
            $instance->checkCooldownAndFlushAfterPersisting($instance, $relationship);
78
        });
79
80
        static::pivotDetached(function ($instance, $secondInstance, $relationship) {
81
            $instance->checkCooldownAndFlushAfterPersisting($instance, $relationship);
82
        });
83
84
        static::pivotUpdated(function ($instance, $secondInstance, $relationship) {
85
            $instance->checkCooldownAndFlushAfterPersisting($instance, $relationship);
86
        });
87
    }
88
89
    public static function destroy($ids)
90
    {
91
        $class = get_called_class();
92
        $instance = new $class;
93
        $instance->flushCache();
94
95
        return parent::destroy($ids);
96
    }
97
98
    public function newEloquentBuilder($query)
99
    {
100
        if (! $this->isCachable()) {
101
            $this->isCachable = false;
102
103
            return new EloquentBuilder($query);
104
        }
105
106
        return new CachedBuilder($query);
107
    }
108
109
    protected function newBelongsToMany(
110
        EloquentBuilder $query,
111
        Model $parent,
112
        $table,
113
        $foreignPivotKey,
114
        $relatedPivotKey,
115
        $parentKey,
116
        $relatedKey,
117
        $relationName = null
118
    ) {
119
        if (method_exists($query->getModel(), "isCachable")
120
            && $query->getModel()->isCachable()
121
        ) {
122
            return new CachedBelongsToMany(
123
                $query,
124
                $parent,
125
                $table,
126
                $foreignPivotKey,
127
                $relatedPivotKey,
128
                $parentKey,
129
                $relatedKey,
130
                $relationName
131
            );
132
        }
133
134
        return new BelongsToMany(
135
            $query,
136
            $parent,
137
            $table,
138
            $foreignPivotKey,
139
            $relatedPivotKey,
140
            $parentKey,
141
            $relatedKey,
142
            $relationName
143
        );
144
    }
145
146
    public function scopeDisableCache(EloquentBuilder $query) : EloquentBuilder
147
    {
148
        if ($this->isCachable()) {
149
            $query = $query->disableModelCaching();
150
        }
151
152
        return $query;
153
    }
154
155
    public function scopeWithCacheCooldownSeconds(
156
        EloquentBuilder $query,
157
        int $seconds = null
158
    ) : EloquentBuilder {
159
        if (! $seconds) {
160
            $seconds = $this->cacheCooldownSeconds;
161
        }
162
163
        $cachePrefix = $this->getCachePrefix();
164
        $modelClassName = get_class($this);
165
        $cacheKey = "{$cachePrefix}:{$modelClassName}-cooldown:seconds";
166
167
        $this->cache()
168
            ->rememberForever($cacheKey, function () use ($seconds) {
169
                return $seconds;
170
            });
171
172
        $cacheKey = "{$cachePrefix}:{$modelClassName}-cooldown:invalidated-at";
173
        $this->cache()
174
            ->rememberForever($cacheKey, function () {
175
                return (new Carbon)->now();
176
            });
177
178
        return $query;
179
    }
180
}
181