Passed
Push — master ( c7ad02...4e76c6 )
by Mike
03:06
created

Clear::flushModelCache()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 1
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
1
<?php namespace GeneaLabs\LaravelModelCaching\Console\Commands;
2
3
use Illuminate\Console\Command;
4
use Illuminate\Support\Collection;
5
6
class Clear extends Command
7
{
8
    protected $signature = 'modelCache:clear {--model=}';
9
    protected $description = 'Flush cache for a given model. If no model is given, entire model-cache is flushed.';
10
11
    public function handle()
12
    {
13
        $option = $this->option('model');
14
15
        if (! $option) {
16
            return $this->flushEntireCache();
17
        }
18
19
        return $this->flushModelCache($option);
20
    }
21
22
    protected function flushEntireCache() : int
23
    {
24
        cache()
25
            ->store(config('laravel-model-caching.store'))
26
            ->flush();
27
28
        $this->info("✔︎ Entire model cache has been flushed.");
29
30
        return 0;
31
    }
32
33
    protected function flushModelCache(string $option) : int
34
    {
35
        $model = new $option;
36
        $usesCachableTrait = $this->getAllTraitsUsedByClass($option)
37
            ->contains("GeneaLabs\LaravelModelCaching\Traits\Cachable");
38
39
        if (! $usesCachableTrait) {
40
            $this->error("'{$option}' is not an instance of CachedModel.");
41
            $this->line("Only CachedModel instances can be flushed.");
42
43
            return 1;
44
        }
45
46
        $model->flushCache();
47
        $this->info("✔︎ Cache for model '{$option}' has been flushed.");
48
49
        return 0;
50
    }
51
52
    protected function getAllTraitsUsedByClass(
53
        string $classname,
54
        bool $autoload = true
55
    ) : Collection {
56
        $traits = collect();
57
58
        if (class_exists($classname, $autoload)) {
59
            $traits = collect(class_uses($classname, $autoload));
60
        }
61
62
        $parentClass = get_parent_class($classname);
63
64
        if ($parentClass) {
65
            $traits = $traits
66
                ->merge($this->getAllTraitsUsedByClass($parentClass, $autoload));
67
        }
68
69
        return $traits;
70
    }
71
}
72