TokenRepository::setToken()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 18
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 27
rs 9.6666
1
<?php
2
3
namespace App\Repositories;
4
5
use App\Token as Model;
6
use App\Traits\CaptureIpTrait;
7
use Auth;
8
use Carbon\Carbon;
9
use Cookie;
10
use Illuminate\Support\Str;
11
use Jenssegers\Agent\Agent;
12
13
// use Cache;
14
15
class TokenRepository extends InitRepository
16
{
17
    public function __construct()
18
    {
19
        parent::__construct();
20
    }
21
22
    protected function getModelClass()
23
    {
24
        return Model::class;
25
    }
26
27
    public function setToken($user_id)
28
    {
29
        $token = new Model();
30
31
        $ipAddress = new CaptureIpTrait();
32
        $agent = new Agent();
33
34
        $browser = $agent->browser();
35
        $platform = $agent->platform();
36
37
        $token->device = $agent->device();
38
        $token->browser = $browser.'('.$agent->version($browser).')';
0 ignored issues
show
Bug introduced by
Are you sure $agent->version($browser) of type double|false|mixed can be used in concatenation? ( Ignorable by Annotation )

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

38
        $token->browser = $browser.'('./** @scrutinizer ignore-type */ $agent->version($browser).')';
Loading history...
39
        $token->system = $platform.'('.$agent->version($platform).')';
0 ignored issues
show
Bug introduced by
Are you sure $agent->version($platform) of type double|false|mixed can be used in concatenation? ( Ignorable by Annotation )

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

39
        $token->system = $platform.'('./** @scrutinizer ignore-type */ $agent->version($platform).')';
Loading history...
40
41
        $token->user_id = $user_id;
42
        $token->last_ip = $ipAddress->getClientIp();
43
        $unique_token = Str::random(60);
0 ignored issues
show
Unused Code introduced by
The assignment to $unique_token is dead and can be removed.
Loading history...
44
45
        do {
46
            $unique_token = Str::random(60);
47
        } while (!empty(Model::where('api_token', $unique_token)->first()));
48
49
        $token->api_token = $unique_token;
50
        $token->login_at = Carbon::now();
51
        $token->save();
52
53
        return $token;
54
    }
55
56
    public function clear_token($token)
57
    {
58
        $data = Model::where('api_token', $token)->first();
59
60
        if (isset($data)) {
61
            cache()->forget('t_'.$token);
62
            $data->delete();
63
        }
64
        Cookie::queue(Cookie::forget('apiToken'));
65
        Auth::logout();
66
67
        return true;
68
    }
69
}
70