OneTimeToken::codeMatches()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 9
rs 10
1
<?php
2
3
namespace ArgentCrusade\Stronghold;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Eloquent\Model;
8
9
/**
10
 * Class OneTimeToken
11
 *
12
 * @property int $id
13
 * @property int|string $user_id
14
 * @property string $operation
15
 * @property string $identifier
16
 * @property int $code
17
 * @property string|null $payload
18
 * @property \Carbon\Carbon|null $expires_at
19
 * @property \Carbon\Carbon|null $used_at
20
 * @property-read \Carbon\Carbon $created_at
21
 * @property-read \Carbon\Carbon $updated_at
22
 */
23
class OneTimeToken extends Model
24
{
25
    protected $fillable = [
26
        'user_id', 'operation', 'identifier', 'code',
27
        'payload', 'expires_at', 'used_at',
28
    ];
29
30
    protected $casts = [
31
        'code' => 'integer',
32
        'expires_at' => 'datetime',
33
        'used_at' => 'datetime',
34
    ];
35
36
    /**
37
     * Determines whether the given code identified by given identifier matches.
38
     *
39
     * @param string $identifier
40
     * @param int    $code
41
     *
42
     * @return bool
43
     */
44
    public static function codeMatches(string $identifier, int $code)
45
    {
46
        $token = static::identifiedBy($identifier);
47
48
        if (is_null($token)) {
49
            return false;
50
        }
51
52
        return $token->code === $code;
53
    }
54
55
    /**
56
     * Get the one time token identified by given identifier.
57
     *
58
     * @param string $identifier
59
     *
60
     * @return OneTimeToken|null
61
     */
62
    public static function identifiedBy(string $identifier)
63
    {
64
        return static::where('identifier', $identifier)->first();
65
    }
66
67
    /**
68
     * Get first unused token for the given user ID.
69
     *
70
     * @param int|string $userId
71
     * @param string     $operation = null
72
     *
73
     * @return Builder
74
     */
75
    public static function unusedFor($userId, string $operation = null)
76
    {
77
        return static::where('user_id', $userId)
78
            ->when(!is_null($operation), function (Builder $query) use ($operation) {
79
                $query->where('operation', $operation);
80
            })
81
            ->where('expires_at', '>', Carbon::now())
82
            ->whereNull('used_at');
83
    }
84
}
85