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

DatabaseTokenRepository   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 15
c 1
b 0
f 0
dl 0
loc 28
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A persist() 0 7 1
A retrieveByCipherText() 0 5 2
A createOtpToken() 0 9 1
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