Passed
Push — master ( 60d66c...bc3293 )
by Mike
03:04
created

CachedModel   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
c 0
b 0
f 0
dl 0
loc 45
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A cache() 0 10 2
A flushCache() 0 3 1
A newEloquentBuilder() 0 3 1
A boot() 0 20 1
1
<?php namespace GeneaLabs\LaravelModelCaching;
2
3
use GeneaLabs\LaravelModelCaching\Builder;
4
use Illuminate\Cache\CacheManager;
5
use Illuminate\Cache\TaggableStore;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Relations\Relation;
8
use LogicException;
9
10
use Illuminate\Cache\TaggedCache;
11
12
abstract class CachedModel extends Model
13
{
14
    public function newEloquentBuilder($query)
15
    {
16
        return new Builder($query);
17
    }
18
19
    public static function boot()
20
    {
21
        parent::boot();
22
        $class = get_called_class();
23
        $instance = new $class;
24
25
        static::created(function () use ($instance) {
26
            $instance->flushCache();
27
        });
28
29
        static::deleted(function () use ($instance) {
30
            $instance->flushCache();
31
        });
32
33
        static::saved(function () use ($instance) {
34
            $instance->flushCache();
35
        });
36
37
        static::updated(function () use ($instance) {
38
            $instance->flushCache();
39
        });
40
    }
41
42
    public function cache(array $tags = [])
43
    {
44
        $cache = cache();
45
46
        if (is_subclass_of(cache()->getStore(), TaggableStore::class)) {
47
            array_push($tags, str_slug(get_called_class()));
48
            $cache = cache()->tags($tags);
49
        }
50
51
        return $cache;
52
    }
53
54
    public function flushCache(array $tags = [])
55
    {
56
        $this->cache($tags)->flush();
57
    }
58
}
59