CacheGc::handle()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 5
eloc 16
c 2
b 0
f 1
nc 4
nop 0
dl 0
loc 22
rs 9.4222
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: hugh.li
5
 * Date: 2021/6/9
6
 * Time: 7:25 下午.
7
 */
8
9
namespace HughCube\Laravel\OTS\Commands;
10
11
use Aliyun\OTS\OTSClientException;
12
use Aliyun\OTS\OTSServerException;
13
use Carbon\Carbon;
14
use HughCube\Laravel\OTS\Cache\Store;
15
use Illuminate\Console\Command;
16
use Illuminate\Contracts\Cache\Repository;
17
use Illuminate\Support\Facades\Cache;
18
19
class CacheGc extends Command
20
{
21
    /**
22
     * The console command name.
23
     *
24
     * @var string
25
     */
26
    protected $signature = 'ots:gc-cache
27
                        {--cache=ots : name of cache. }
28
                        {--expired_duration=2592000 : The data that has expired is cleared. }';
29
30
    /**
31
     * The console command description.
32
     *
33
     * @var string
34
     */
35
    protected $description = 'ots cache gc';
36
37
    /**
38
     * @throws OTSClientException
39
     * @throws OTSServerException
40
     *
41
     * @return void
42
     */
43
    public function handle()
44
    {
45
        $store = $this->getCache()->getStore();
46
        if (!$store instanceof Store) {
47
            $this->warn('Only OTS cache can be processed.');
48
49
            return;
50
        }
51
52
        $count = 0;
53
        $page = 200;
54
        while (true) {
55
            $deletedCount = $store->flushExpiredRows($page, $this->getExpiredDuration());
56
            $this->comment(sprintf(
57
                '%s Delete %s rows from the "%s" table, The total number of deleted rows is %s.',
58
                Carbon::now()->format('Y-m-d H:i:s.u'),
59
                $deletedCount,
60
                $store->getTable(),
61
                ($count += $deletedCount)
62
            ));
63
            if (0 >= $deletedCount || $deletedCount < $page) {
64
                break;
65
            }
66
        }
67
    }
68
69
    protected function getCache(): Repository
70
    {
71
        return Cache::store(($this->option('cache') ?: null));
72
    }
73
74
    protected function getExpiredDuration(): int
75
    {
76
        return intval($this->option('expired_duration'));
77
    }
78
}
79