Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
16 / 16 |
|
100.00% |
5 / 5 |
CRAP | |
100.00% |
1 / 1 |
DatabaseHandler | |
100.00% |
16 / 16 |
|
100.00% |
5 / 5 |
6 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
read | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
write | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
1 | |||
destroy | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
gc | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | |
3 | declare(strict_types=1); |
4 | |
5 | namespace Engelsystem\Http\SessionHandlers; |
6 | |
7 | use Engelsystem\Database\Database; |
8 | use Engelsystem\Helpers\Carbon; |
9 | use Engelsystem\Models\Session; |
10 | |
11 | class DatabaseHandler extends AbstractHandler |
12 | { |
13 | public function __construct(protected Database $database) |
14 | { |
15 | } |
16 | |
17 | /** |
18 | * {@inheritdoc} |
19 | */ |
20 | public function read(string $id): string |
21 | { |
22 | $session = Session::whereId($id)->first(); |
23 | |
24 | return $session ? $session->payload : ''; |
25 | } |
26 | |
27 | /** |
28 | * {@inheritdoc} |
29 | */ |
30 | public function write(string $id, string $data): bool |
31 | { |
32 | $session = Session::findOrNew($id); |
33 | $session->id = $id; |
34 | $session->payload = $data; |
35 | $session->last_activity = Carbon::now(); |
36 | $session->user_id = auth()->user()?->id; |
37 | $session->save(); |
38 | |
39 | // The save return can't be used directly as it won't change if the second call is in the same second |
40 | return true; |
41 | } |
42 | |
43 | /** |
44 | * {@inheritdoc} |
45 | */ |
46 | public function destroy(string $id): bool |
47 | { |
48 | Session::whereId($id)->delete(); |
49 | |
50 | return true; |
51 | } |
52 | |
53 | /** |
54 | * {@inheritdoc} |
55 | */ |
56 | public function gc(int $max_lifetime): int|false |
57 | { |
58 | $sessionDays = config('session')['lifetime']; |
59 | $deleteBefore = Carbon::now()->subDays($sessionDays); |
60 | |
61 | return Session::where('last_activity', '<', $deleteBefore) |
62 | ->delete(); |
63 | } |
64 | } |