Completed
Push — master ( b0dccf...a37019 )
by Mike
10s
created

CachedModel   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
dl 0
loc 48
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A all() 0 10 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 GeneaLabs\LaravelModelCaching\Traits\Cachable;
5
use Illuminate\Cache\CacheManager;
6
use Illuminate\Cache\TaggableStore;
7
use Illuminate\Cache\TaggedCache;
8
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
9
use Illuminate\Database\Eloquent\Model;
10
use Illuminate\Database\Eloquent\Relations\Relation;
11
use Illuminate\Support\Collection;
12
use LogicException;
13
14
abstract class CachedModel extends Model
15
{
16
    use Cachable;
17
18
    public function newEloquentBuilder($query)
19
    {
20
        if (session('genealabs-laravel-model-caching-is-disabled')) {
21
            session()->forget('genealabs-laravel-model-caching-is-disabled');
22
23
            return new EloquentBuilder($query);
24
        }
25
26
        return new Builder($query);
27
    }
28
29
    public static function boot()
30
    {
31
        parent::boot();
32
        $class = get_called_class();
33
        $instance = new $class;
34
35
        static::created(function () use ($instance) {
36
            $instance->flushCache();
37
        });
38
39
        static::deleted(function () use ($instance) {
40
            $instance->flushCache();
41
        });
42
43
        static::saved(function () use ($instance) {
44
            $instance->flushCache();
45
        });
46
47
        static::updated(function () use ($instance) {
48
            $instance->flushCache();
49
        });
50
    }
51
52
    public static function all($columns = ['*'])
53
    {
54
        $class = get_called_class();
55
        $instance = new $class;
56
        $tags = [str_slug(get_called_class())];
57
        $key = 'genealabslaravelmodelcachingtestsfixturesauthor';
58
59
        return $instance->cache($tags)
60
            ->rememberForever($key, function () use ($columns) {
61
                return parent::all($columns);
62
            });
63
    }
64
}
65