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

CachedModel::getRelationshipFromMethod()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 1
nop 1
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
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