1 | <?php |
||
2 | |||
3 | namespace ThinKit\Console\Commands; |
||
4 | |||
5 | use Carbon\Carbon; |
||
6 | use Illuminate\Console\Command; |
||
7 | use Illuminate\Database\Eloquent\Model; |
||
8 | use Illuminate\Database\Eloquent\Relations\Relation; |
||
9 | use Illuminate\Database\Eloquent\SoftDeletes; |
||
10 | use ThinKit\Models\Expiration\HasExpiration; |
||
11 | |||
12 | class DeleteExpiredCommand extends Command |
||
13 | { |
||
14 | |||
15 | protected $signature = 'thinkit:delete-expired {model} {--force} {--timeout=0}'; |
||
16 | |||
17 | protected $description = ''; |
||
18 | |||
19 | 5 | public function handle() |
|
20 | { |
||
21 | 5 | $modelName = $this->argument('model'); |
|
22 | 5 | $timeoutInMinutes = (int)$this->option('timeout'); |
|
23 | 5 | $isForceDelete = (bool)$this->option('force'); |
|
24 | |||
25 | 5 | if (!is_subclass_of($modelName, Model::class, true)) { |
|
26 | 1 | $modelName = Relation::getMorphedModel($modelName) ?: $modelName; |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
27 | } |
||
28 | |||
29 | 5 | if (!is_subclass_of($modelName, Model::class, true)) { |
|
30 | 1 | $this->error("Model [{$modelName}] name should extends model class"); |
|
31 | |||
32 | 1 | return static::FAILURE; |
|
33 | } |
||
34 | |||
35 | 4 | if (!in_array(HasExpiration::class, class_uses_recursive($modelName))) { |
|
36 | 1 | $this->error("Model [{$modelName}] should use trait 'HasExpiration'"); |
|
37 | |||
38 | 1 | return static::FAILURE; |
|
39 | } |
||
40 | |||
41 | 3 | $query = $modelName::query()->willBeExpiredAt(Carbon::now()->addMinutes($timeoutInMinutes)); |
|
42 | |||
43 | 3 | if ($isForceDelete && in_array(SoftDeletes::class, class_uses_recursive($modelName))) { |
|
44 | do { |
||
45 | 1 | $deleted = $query->limit(100)->forceDelete(); |
|
46 | 1 | } while ($deleted > 0); |
|
47 | } else { |
||
48 | do { |
||
49 | 2 | $deleted = $query->limit(100)->delete(); |
|
50 | 2 | } while ($deleted > 0); |
|
51 | } |
||
52 | |||
53 | |||
54 | 3 | return static::SUCCESS; |
|
55 | } |
||
56 | } |
||
57 |