CreateTokenCommand::handle()   A
last analyzed

Complexity

Conditions 5
Paths 12

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
dl 0
loc 17
ccs 0
cts 14
cp 0
rs 9.4888
c 1
b 0
f 0
cc 5
nc 12
nop 0
crap 30
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Garbuzivan\Laraveltokens\Commands;
6
7
use Carbon\Carbon;
8
use Garbuzivan\Laraveltokens\Exceptions\UserNotExistsException;
9
use Garbuzivan\Laraveltokens\TokenManager;
10
use Illuminate\Console\Command;
11
use Illuminate\Support\Composer;
12
13
class CreateTokenCommand extends Command
14
{
15
    /**
16
     * The console command name.
17
     *
18
     * @var string
19
     */
20
    protected $name = 'tokens:create {title} {day} {user_id} {type?}';
21
22
    /**
23
     * The console command description.
24
     *
25
     * @var string
26
     */
27
    protected $description = 'Создать новый персональный токен ' .
28
    '(tokens:create {title} {количество дней действия или 0 == бессрочно} {user_id} {type?})';
29
30
    /**
31
     * The console command signature.
32
     *
33
     * @var string
34
     */
35
    protected $signature = 'tokens:create {title} {day} {user_id} {type?}';
36
37
    /**
38
     * @var Composer
39
     */
40
    public Composer $composer;
41
42
    /**
43
     * @var TokenManager
44
     */
45
    public TokenManager $TokenManager;
46
47
    /**
48
     * Create a new command instance.
49
     */
50
    public function __construct(TokenManager $TokenManager)
51
    {
52
        parent::__construct();
53
        $this->TokenManager = $TokenManager;
54
    }
55
56
    /**
57
     * Execute the command.
58
     *
59
     * @return mixed
60
     */
61
    public function handle()
62
    {
63
        $arguments = $this->arguments();
64
        $title = $arguments['title'] ?? date('Y-m-d H:i:s');
65
        $user_id = $arguments['user_id'] ? intval($arguments['user_id']) : null;
66
        $type = $arguments['type'] ?? $this->TokenManager->getDefaultMorph();
67
        $day = intval($arguments['day']);
68
        $expiration = $day > 0 ? Carbon::now()->addDays($day) : null;
69
        try {
70
            $token = $this->TokenManager->createAccessToken($title, $expiration, $user_id, $type);
71
        } catch (UserNotExistsException $e) {
72
            $this->line('Пользователь ID ' . $user_id . ' не найден.');
73
            return 1;
74
        }
75
        $date = is_null($expiration) ? 'навсегда' : 'до ' . $expiration->format('Y-m-d H:i:s');
76
        $this->line('Персональный токен ' . $token->token . ' создан '. $date . '.');
77
        return 1;
78
    }
79
}
80