LoginLoggable::logLogin()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 2
rs 10
1
<?php
2
3
namespace Moecasts\Laravel\UserLoginLog\Traits;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Eloquent\Relations\MorphMany;
7
use Jenssegers\Agent\Agent;
8
use Moecasts\Laravel\UserLoginLog\Cacher;
9
use Moecasts\Laravel\UserLoginLog\DeviceType;
10
use Moecasts\Laravel\UserLoginLog\Models\UserLoginLog;
11
12
trait LoginLoggable
13
{
14 7
    public function loginLogs(): MorphMany
15
    {
16 7
        return $this->morphMany(UserLoginLog::class, 'loggable');
0 ignored issues
show
Bug introduced by
It seems like morphMany() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

16
        return $this->/** @scrutinizer ignore-call */ morphMany(UserLoginLog::class, 'loggable');
Loading history...
17
    }
18
19 5
    public function logLogin($seconds = null): ?UserLoginLog
20
    {
21 5
        $log = null;
22 5
        if ($this->isNewLogin()) {
23 5
            $log = $this->createLoginLog();
24
        }
25
26 5
        Cacher::setCache($this, $seconds);
27
28 5
        return $log;
29
    }
30
31 6
    public function createLoginLog(): UserLoginLog
32
    {
33 6
        $agent = new Agent();
34 6
        $log = new UserLoginLog([
35 6
            'ip' => request()->ip(),
36 6
            'device' => $agent->device(),
37 6
            'platform' => $agent->platform(),
38 6
            'browser' => $agent->browser(),
39 6
            'device_type' => DeviceType::getValue($agent),
40 6
            'login_at' => Carbon::now(),
41
        ]);
42
43 6
        $log->platform_version = $agent->version($log->platform);
44 6
        $log->browser_version = $agent->version($log->browser);
45
46 6
        $this->loginLogs()->save($log);
47 6
        return $log;
48
    }
49
50 5
    public function isNewLogin(): bool
51
    {
52 5
        return !Cacher::hasCache($this);
53
    }
54
}
55