Passed
Push — main ( e492c9...632610 )
by Yaroslav
02:58
created

DeleteExpiredCommand   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 24
c 1
b 0
f 0
dl 0
loc 43
ccs 19
cts 19
cp 1
rs 10
wmc 9

1 Method

Rating   Name   Duplication   Size   Complexity  
B handle() 0 36 9
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
It seems like $modelName can also be of type array; however, parameter $alias of Illuminate\Database\Eloq...tion::getMorphedModel() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

26
            $modelName = Relation::getMorphedModel(/** @scrutinizer ignore-type */ $modelName) ?: $modelName;
Loading history...
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