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