Passed
Pull Request — master (#274)
by
unknown
03:01
created

ModelCaching::destroy()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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