CleanActivitylogCommand::handle()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 1.0004

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 22
ccs 12
cts 13
cp 0.9231
crap 1.0004
rs 9.568
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Activitylog;
4
5
use Carbon\Carbon;
6
use Illuminate\Console\Command;
7
use Illuminate\Database\Eloquent\Builder;
8
9
class CleanActivitylogCommand extends Command
10
{
11
    protected $signature = 'activitylog:clean
12
                            {log? : (optional) The log name that will be cleaned.}
13
                            {--days= : (optional) Records older than this number of days will be cleaned.}';
14
15
    protected $description = 'Clean up old records from the activity log.';
16
17 7
    public function handle()
18
    {
19 7
        $this->comment('Cleaning activity log...');
20
21 7
        $log = $this->argument('log');
22
23 7
        $maxAgeInDays = $this->option('days') ?? config('activitylog.delete_records_older_than_days');
24
25 7
        $cutOffDate = Carbon::now()->subDays($maxAgeInDays)->format('Y-m-d H:i:s');
26
27 7
        $activity = ActivitylogServiceProvider::getActivityModelInstance();
28
29 7
        $amountDeleted = $activity::where('created_at', '<', $cutOffDate)
30
            ->when($log !== null, function (Builder $query) use ($log) {
31
                $query->inLog($log);
32 7
            })
33 7
            ->delete();
34
35 7
        $this->info("Deleted {$amountDeleted} record(s) from the activity log.");
36
37 7
        $this->comment('All done!');
38 7
    }
39
}
40