1
|
|
|
<?php namespace GeneaLabs\LaravelModelCaching\Console\Commands; |
2
|
|
|
|
3
|
|
|
use Illuminate\Console\Command; |
4
|
|
|
use Illuminate\Support\Collection; |
5
|
|
|
|
6
|
|
|
class Flush extends Command |
7
|
|
|
{ |
8
|
|
|
protected $signature = 'modelCache:flush {--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(string $classname, bool $autoload = true) : Collection |
53
|
|
|
{ |
54
|
|
|
$traits = collect(); |
55
|
|
|
|
56
|
|
|
if (class_exists($classname, $autoload)) { |
57
|
|
|
$traits = collect(class_uses($classname, $autoload)); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$parentClass = get_parent_class($classname); |
61
|
|
|
|
62
|
|
|
if ($parentClass) { |
63
|
|
|
$traits = $traits->merge($this->getAllTraitsUsedByClass($parentClass, $autoload)); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $traits; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|