PurgeUsers   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 68
rs 10
c 0
b 0
f 0
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A handle() 0 47 5
1
<?php
2
3
namespace App\Console\Commands;
4
5
use App\User;
6
use Carbon\Carbon;
7
8
class PurgeUsers extends Command
9
{
10
    /**
11
     * The name and signature of the console command.
12
     *
13
     * @var string
14
     */
15
    protected $signature = 'bibrex:purge-users';
16
17
    /**
18
     * The console command description.
19
     *
20
     * @var string
21
     */
22
    protected $description = 'Purge inactive users.';
23
24
    /**
25
     * Execute the console command.
26
     *
27
     * @return mixed
28
     */
29
    public function handle()
30
    {
31
        $daysLocal = (int) config('bibrex.storage_time.local_users');
32
        if ($daysLocal <= 0) {
33
            $this->logError('The `bibrex.storage_time.local_users` config value is invalid.');
34
            return;
35
        }
36
37
        $daysImported = (int) config('bibrex.storage_time.imported_users');
38
        if ($daysImported <= 0) {
39
            $this->logError('The `bibrex.storage_time.imported_users` config value is invalid.');
40
            return;
41
        }
42
43
        $n = 0;
44
45
        // Check imported users
46
        $users = User::doesntHave('loans')
47
            ->where('last_loan_at', '<', Carbon::now()->subDays($daysImported))
48
            ->where('in_alma', '=', 1)
49
            ->get();
50
51
        foreach ($users as $user) {
52
            $this->logInfo(
53
                "Sletting av inaktive brukere: Slettet {$user->name} ({$user->id})," .
54
                " sist aktiv {$user->last_loan_at->toDateString()}."
55
            );
56
            $user->delete();
57
            $n++;
58
        }
59
60
        // Check local users
61
        $users = User::doesntHave('loans')
62
            ->where('last_loan_at', '<', Carbon::now()->subDays($daysLocal))
63
            ->where('in_alma', '=', 0)
64
            ->get();
65
66
        foreach ($users as $user) {
67
            $this->logInfo(
68
                "Sletting av inaktive brukere: Slettet {$user->name} ({$user->id})," .
69
                " sist aktiv {$user->last_loan_at->toDateString()}."
70
            );
71
            $user->delete();
72
            $n++;
73
        }
74
75
        $this->info("Slettet $n brukere.");
76
    }
77
}
78