DeleteExpiredTokensCommand::removeExpiredTokens()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 9
rs 10
1
<?php
2
3
namespace App\Console\Commands;
4
5
use App\Models\UserToken;
6
use App\Services\LogService;
7
use Carbon\Carbon;
8
use Exception;
9
use Illuminate\Console\Command;
10
use Illuminate\Support\Facades\DB;
11
use Illuminate\Support\Facades\Log;
12
use Throwable;
13
14
/**
15
 * Class DeleteExpiredTokensCommand.
16
 *
17
 * Delete all expired token.
18
 * Should be running once a day.
19
 *
20
 * @package App\Console\Commands
21
 */
22
class DeleteExpiredTokensCommand extends Command
23
{
24
    /** @var string */
25
    protected $signature = 'delete:expiredTokens';
26
27
    /** @var string */
28
    protected $description = 'Remove expired tokens from database.';
29
30
    /**
31
     * Command handle.
32
     */
33
    public function handle()
34
    {
35
        try {
36
            $this->info('[' . Carbon::now()->format('Y-m-d H:i:s') . ']: Command [delete:expiredTokens] started.');
37
38
            DB::beginTransaction();
39
40
            $this->removeExpiredTokens();
41
42
            DB::commit();
43
44
            $this->info('[' . Carbon::now()->format('Y-m-d H:i:s') . ']: Command [delete:expiredTokens] ended.');
45
        } catch (Throwable $t) {
46
            Log::error(LogService::getThrowableTraceAsString($t));
47
48
            $this->error($t->getMessage());
49
        }
50
    }
51
52
    /**
53
     * Remove expired tokens.
54
     * We delete separate each token in case we add something to model boot.
55
     *
56
     * @throws Exception
57
     */
58
    private function removeExpiredTokens()
59
    {
60
        $userTokens = UserToken::where('expire_on', '<=', Carbon::now()->format('Y-m-d H:i:s'))
61
                               ->get();
62
63
        $this->info('[' . Carbon::now()->format('Y-m-d H:i:s') . ']: Found ' . $userTokens->count() . ' tokens to be removed.');
64
65
        foreach ($userTokens as $userToken) {
66
            $userToken->delete();
67
        }
68
    }
69
}
70