Passed
Pull Request — master (#20)
by Hilmi Erdem
10:06
created

DatabaseTokenRepository::persist()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 7
rs 10
1
<?php
2
/*
3
 * Copyright (c) 2021. Hilmi Erdem Keren
4
 * license MIT
5
 */
6
7
namespace Erdemkeren\Otp\Repositories;
8
9
use Erdemkeren\Otp\OtpToken;
10
use Illuminate\Support\Facades\DB;
11
use Erdemkeren\Otp\Contracts\TokenRepositoryContract;
12
13
class DatabaseTokenRepository implements TokenRepositoryContract
14
{
15
    public function retrieveByCipherText(string $cipherText): ?OtpToken
16
    {
17
        $result = DB::table('otp_tokens')->where('cipher_text', $cipherText)->first();
18
19
        return $result ? $this->createOtpToken($result) : null;
20
    }
21
22
    public function persist(OtpToken $token): bool
23
    {
24
        return DB::transaction(
25
            fn (): bool => DB::table('otp_tokens')->updateOrInsert([
26
                'authenticable_id' => $token->authenticableId(),
27
                'cipher_text'      => $token->cipherText(),
28
            ], $token->withoutPlainText()->toArray())
29
        );
30
    }
31
32
    private function createOtpToken(object $result): OtpToken
33
    {
34
        return new OtpToken([
35
            'authenticable_id' => $result->authenticable_id,
36
            'cipher_text' => $result->cipher_text,
37
            'format' => $result->format,
38
            'expiry_time' => $result->expiry_time,
39
            'created_at' => $result->created_at,
40
            'updated_at' => $result->updated_at,
41
        ]);
42
    }
43
}
44