Completed
Pull Request — master (#40)
by Mike
04:49
created

CachedModel   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
dl 0
loc 70
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A cache() 0 10 2
A flushCache() 0 3 1
A all() 0 10 1
A disableCache() 0 5 1
A newEloquentBuilder() 0 9 2
A boot() 0 20 1
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