LoginLogMigration::handle()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 5
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
namespace App\Console\Commands\Migrations;
4
5
use App\Entities\LoginLog;
6
use App\Entities\User;
7
use Carbon\Carbon;
8
use Illuminate\Console\Command;
9
10
class LoginLogMigration extends Migration
11
{
12
    /**
13
     * @param Command $command
14
     */
15
    public function handle($command)
16
    {
17
        $command->info('Migrating Login Logs...');
18
        User::chunk(100, function ($users) {
19
            foreach ($users as $user) {
20
                $this->processUser($user);
21
            }
22
        });
23
        $command->info('Migrating Login Logs Done');
24
    }
25
26
    private function processUser($user)
27
    {
28
        $logs = $this->getUserRecentLogs($user, 90);
29
        foreach ($logs as $log) {
30
            $newLog = new LoginLog();
31
            $newLog->user_id = $user->id;
32
            $newLog->ip = $log->ip;
33
            $newLog->password = $log->password;
34
            $newLog->status = LoginLog::ST_OK;
35
            $newLog->created_at = $log->time;
36
            $newLog->save();
37
        }
38
    }
39
40
    /**
41
     * @param User $user
42
     */
43
    private function getUserRecentLogs($user, $days)
44
    {
45
        $now = Carbon::now()->subDays($days)->setTime(0, 0);
46
        $logs = $this->getTable()->where('user_id', $user->username)
47
                     ->where('time', $now, '>')
48
                     ->orderBy('time', 'asc')
49
                     ->get();
50
51
        if ($logs->count() < 10) {
52
            $logs = $this->getTable()->where('user_id', $user->username)
53
                         ->limit(10)
54
                         ->orderBy('time', 'desc')
55
                         ->get();
56
            $logs = $logs->reverse();
57
        }
58
59
        return $logs;
60
    }
61
62
    private function getTable()
63
    {
64
        return $this->getConnection()->table('loginlog');
65
    }
66
}
67