Completed
Push — master ( db70b3...5ed9da )
by Mike
12:00 queued 06:05
created

CachedModel::boot()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 0
1
<?php namespace GeneaLabs\LaravelModelCaching;
2
3
use GeneaLabs\LaravelModelCaching\CachedBuilder as Builder;
4
use Illuminate\Cache\CacheManager;
5
use Illuminate\Cache\TaggableStore;
6
use Illuminate\Cache\TaggedCache;
7
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
8
use Illuminate\Database\Eloquent\Model;
9
use Illuminate\Database\Eloquent\Relations\Relation;
10
use Illuminate\Support\Collection;
11
use LogicException;
12
13
abstract class CachedModel extends Model
14
{
15
    public function newEloquentBuilder($query)
16
    {
17
        if (session('genealabs-laravel-model-caching-is-disabled')) {
18
            session()->forget('genealabs-laravel-model-caching-is-disabled');
19
20
            return new EloquentBuilder($query);
21
        }
22
23
        return new Builder($query);
24
    }
25
26
    public static function boot()
27
    {
28
        parent::boot();
29
        $class = get_called_class();
30
        $instance = new $class;
31
32
        static::created(function () use ($instance) {
33
            $instance->flushCache();
34
        });
35
36
        static::deleted(function () use ($instance) {
37
            $instance->flushCache();
38
        });
39
40
        static::saved(function () use ($instance) {
41
            $instance->flushCache();
42
        });
43
44
        static::updated(function () use ($instance) {
45
            $instance->flushCache();
46
        });
47
    }
48
49
    public function cache(array $tags = [])
50
    {
51
        $cache = cache();
52
53
        if (is_subclass_of($cache->getStore(), TaggableStore::class)) {
54
            array_push($tags, str_slug(get_called_class()));
55
            $cache = $cache->tags($tags);
56
        }
57
58
        return $cache;
59
    }
60
61
    public function disableCache() : self
62
    {
63
        session(['genealabs-laravel-model-caching-is-disabled' => true]);
64
65
        return $this;
66
    }
67
68
    public function flushCache(array $tags = [])
69
    {
70
        $this->cache($tags)->flush();
71
    }
72
73
    public static function all($columns = ['*'])
74
    {
75
        $class = get_called_class();
76
        $instance = new $class;
77
        $tags = [str_slug(get_called_class())];
78
        $key = 'genealabslaravelmodelcachingtestsfixturesauthor';
79
80
        return $instance->cache($tags)
81
            ->rememberForever($key, function () use ($columns) {
82
                return parent::all($columns);
83
            });
84
    }
85
}
86