Passed
Push — main ( 5a9537...12e7e2 )
by Garbuz
02:53
created

AccessTokenRepository::getAccessTokenById()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 1
c 2
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Garbuzivan\Laraveltokens\Repositories;
6
7
use Carbon\Carbon;
8
use DateTime;
9
use Garbuzivan\Laraveltokens\Exceptions\UserNotExistsException;
10
use Garbuzivan\Laraveltokens\Interfaces\AccessTokenRepositoryInterface;
11
use Garbuzivan\Laraveltokens\Models\AccessToken;
12
use Illuminate\Contracts\Container\BindingResolutionException;
13
use Illuminate\Database\Eloquent\Collection;
14
use Illuminate\Support\Facades\DB;
15
16
class AccessTokenRepository implements AccessTokenRepositoryInterface
17
{
18
    /**
19
     * Создать токен
20
     *
21
     * @param string        $title      - заголовок токена
22
     * @param DateTime|null $expiration - до когда действует токен, null - бессрочно
23
     * @param int           $user_id    - ID клиента
24
     * @param string        $user_type  - класс полиморфной связи
25
     * @param string        $token      - токен
26
     *
27
     * @return AccessToken
28
     */
29
    public function createAccessToken(
30
        string    $title,
31
        ?DateTime $expiration = null,
32
        int       $user_id,
33
        string    $user_type,
34
        string    $token
35
    ): AccessToken {
36
        return AccessToken::create([
37
            'token'      => $token,
38
            'user_id'    => $user_id,
39
            'user_type'  => $user_type,
40
            'title'      => $title,
41
            'expiration' => $expiration,
42
        ]);
43
    }
44
45
    /**
46
     * Удалить токен по ID токена
47
     *
48
     * @param int $token_id - ID токена
49
     *
50
     * @return bool
51
     */
52
    public function deleteAccessTokenById(int $token_id): bool
53
    {
54
        return (bool)AccessToken::where('id', $token_id)->delete();
55
    }
56
57
    /**
58
     * Удалить токен
59
     *
60
     * @param string $token
61
     *
62
     * @return bool
63
     */
64
    public function deleteAccessToken(string $token): bool
65
    {
66
        return (bool)AccessToken::where('token', $token)->delete();
67
    }
68
69
    /**
70
     * Удалить все токены пользователя по id пользователя
71
     *
72
     * @param int    $user_id
73
     * @param string $user_type
74
     *
75
     * @return bool
76
     */
77
    public function deleteAccessTokenByUser(int $user_id, string $user_type): bool
78
    {
79
        return (bool)AccessToken::where('user_id', $user_id)->where('user_type', $user_type)->delete();
80
    }
81
82
    /**
83
     * Очистить таблицу токенов
84
     *
85
     * @return bool
86
     */
87
    public function deleteAllAccessToken(): bool
88
    {
89
        DB::table('access_tokens')->truncate();
90
        return true;
91
    }
92
93
    /**
94
     * Деактивировать токен (прекратить срок действия токена) по ID токена
95
     *
96
     * @param int $token_id - ID токена
97
     *
98
     * @return bool
99
     */
100
    public function deactivationAccessTokenById(int $token_id): bool
101
    {
102
        return (bool)AccessToken::where('id', $token_id)->update([
103
            'expiration' => Carbon::now()->subMinutes(),
104
        ]);
105
    }
106
107
    /**
108
     * Деактивировать токен (прекратить срок действия токена) по токену
109
     *
110
     * @param string $token
111
     *
112
     * @return bool
113
     */
114
    public function deactivationAccessToken(string $token): bool
115
    {
116
        return (bool)AccessToken::where('token', $token)->update([
117
            'expiration' => Carbon::now()->subMinutes(),
118
        ]);
119
    }
120
121
    /**
122
     * Деактивировать токен (прекратить срок действия токена) по id пользователя
123
     *
124
     * @param int    $user_id
125
     * @param string $user_type
126
     *
127
     * @return bool
128
     */
129
    public function deactivationAccessTokenByUser(int $user_id, string $user_type): bool
130
    {
131
        return (bool)AccessToken::where('user_id', $user_id)
132
            ->where('user_type', $user_type)
133
            ->update([
134
                'expiration' => Carbon::now()->subMinutes(),
135
            ]);
136
    }
137
138
    /**
139
     * Продлить срок действия токена по id токена
140
     *
141
     * @param int           $token_id
142
     * @param DateTime|null $expiration
143
     *
144
     * @return bool
145
     */
146
    public function prolongationAccessTokenById(int $token_id, ?DateTime $expiration = null): bool
147
    {
148
        return (bool)AccessToken::where('id', $token_id)->update(['expiration' => $expiration]);
149
    }
150
151
    /**
152
     * Продлить срок действия токена
153
     *
154
     * @param string        $token
155
     * @param DateTime|null $expiration
156
     *
157
     * @return bool
158
     */
159
    public function prolongationAccessToken(string $token, ?DateTime $expiration = null): bool
160
    {
161
        return (bool)AccessToken::where('token', $token)->update(['expiration' => $expiration]);
162
    }
163
164
    /**
165
     * Продлить срок действия всех токенов по id пользователя
166
     *
167
     * @param int           $user_id
168
     * @param string        $user_type
169
     * @param DateTime|null $expiration
170
     *
171
     * @return bool
172
     */
173
    public function prolongationAccessTokenByUser(int $user_id, string $user_type, ?DateTime $expiration = null): bool
174
    {
175
        return (bool)AccessToken::where('user_id', $user_id)
176
            ->where('user_type', $user_type)
177
            ->update(['expiration' => $expiration]);
178
    }
179
180
    /**
181
     * Получить список токенов по ID пользователя
182
     *
183
     * @param int    $user_id
184
     * @param string $user_type
185
     *
186
     * @return Collection|null
187
     */
188
    public function getAccessTokenByUser(int $user_id, string $user_type): ?Collection
189
    {
190
        return AccessToken::where('user_id', $user_id)
191
            ->where('user_type', $user_type)
192
            ->orderByDesc('expiration')->get();
193
    }
194
195
    /**
196
     * Получить токен по ID
197
     *
198
     * @param int $token_id
199
     *
200
     * @return AccessToken|null
201
     */
202
    public function getAccessTokenById(int $token_id): ?AccessToken
203
    {
204
        return AccessToken::where('id', $token_id)->first();
205
    }
206
207
    /**
208
     * Получить данные о токене
209
     *
210
     * @param string $token
211
     *
212
     * @return AccessToken|null
213
     */
214
    public function getAccessToken(string $token): ?AccessToken
215
    {
216
        return AccessToken::where('token', $token)->first();
217
    }
218
219
    /**
220
     * Фиксация последней активности токена
221
     *
222
     * @param string $token
223
     *
224
     * @return bool
225
     */
226
    public function setLastUseAccessToken(string $token): bool
227
    {
228
        return (bool)AccessToken::where('token', $token)->update([
229
            'last_use' => Carbon::now()->subMinutes(),
230
        ]);
231
    }
232
233
    /**
234
     * Проверка полиморфной связи
235
     *
236
     * @param int    $user_id
237
     * @param string $user_type
238
     *
239
     * @return void
240
     * @throws UserNotExistsException
241
     */
242
    public function isMorph(int $user_id, string $user_type): void
243
    {
244
        $user = app($user_type)->/** @scrutinizer ignore-call */ where('id', $user_id)->first();
245
        if (is_null($user)) {
246
            throw new UserNotExistsException;
247
        }
248
    }
249
}
250