Passed
Push — master ( 6760ee...9e3b1c )
by Ion
02:46
created

DeleteExpiredTokensCommand::removeExpiredTokens()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
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 11
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\Database\Eloquent\Collection;
11
use Illuminate\Support\Facades\DB;
12
use Illuminate\Support\Facades\Log;
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 (Exception $e) {
46
            Log::error(LogService::getExceptionTraceAsString($e));
47
48
            $this->error($e->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
        /** @var Collection $userTokens */
61
        $userTokens = UserToken::where('expire_on', '<=', Carbon::now()->format('Y-m-d H:i:s'))
62
            ->get();
63
64
        $this->info('[' . Carbon::now()->format('Y-m-d H:i:s') . ']: Found ' . $userTokens->count() . ' tokens to be removed.');
65
66
        /** @var UserToken $userToken */
67
        foreach ($userTokens as $userToken) {
68
            $userToken->delete();
69
        }
70
    }
71
}
72