Passed
Push — master ( a50549...138a43 )
by Koen
03:13
created

Repository::put()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 5
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Auth\Dispensary;
6
7
use App\Models\Dispense;
8
use Carbon\Carbon;
9
10
final class Repository
11
{
12
    public function put(string $key, string $token, int $ttl): void
13
    {
14
        Dispense::query()->updateOrCreate(['key' => $key], [
15
            'token'      => $token,
16
            'expires_at' => Carbon::now()->addSeconds($ttl),
17
        ]);
18
    }
19
20
    public function get(string $key): ?string
21
    {
22
        $dispense = Dispense::query()->where('key', $key)->first();
23
24
        if (! $dispense instanceof Dispense) {
25
            return null;
26
        }
27
28
        if ($dispense->getExpiresAt()->greaterThan(Carbon::now())) {
29
            $dispense->delete();
30
31
            return null;
32
        }
33
34
        return $dispense->getToken();
35
    }
36
37
    public function clear(): void
38
    {
39
        Dispense::query()->delete();
40
    }
41
}
42