summaryrefslogtreecommitdiff
path: root/src/Http/SessionHandlers/DatabaseHandler.php
blob: 8df7028755a66cfd4e9eedc44c1ede51a3f9cd1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php

namespace Engelsystem\Http\SessionHandlers;

use Engelsystem\Database\Database;
use Illuminate\Database\Query\Builder as QueryBuilder;

class DatabaseHandler extends AbstractHandler
{
    /** @var Database */
    protected $database;

    /**
     * @param Database $database
     */
    public function __construct(Database $database)
    {
        $this->database = $database;
    }

    /**
     * {@inheritdoc}
     */
    public function read($id): string
    {
        $session = $this->getQuery()
            ->where('id', '=', $id)
            ->first();

        return $session ? $session->payload : '';
    }

    /**
     * {@inheritdoc}
     */
    public function write($id, $data): bool
    {
        $values = [
            'payload'       => $data,
            'last_activity' => $this->getCurrentTimestamp(),
        ];

        $session = $this->getQuery()
            ->where('id', '=', $id)
            ->first();

        if (!$session) {
            return $this->getQuery()
                ->insert($values + [
                        'id' => $id,
                    ]);
        }

        $this->getQuery()
            ->where('id', '=', $id)
            ->update($values);

        // The update return can't be used directly because it won't change if the second call is in the same second
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function destroy($id): bool
    {
        $this->getQuery()
            ->where('id', '=', $id)
            ->delete();

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function gc($maxLifetime): bool
    {
        $timestamp = $this->getCurrentTimestamp(-$maxLifetime);

        $this->getQuery()
            ->where('last_activity', '<', $timestamp)
            ->delete();

        return true;
    }

    /**
     * @return QueryBuilder
     */
    protected function getQuery(): QueryBuilder
    {
        return $this->database
            ->getConnection()
            ->table('sessions');
    }

    /**
     * Format the SQL timestamp
     *
     * @param int $diff
     * @return string
     */
    protected function getCurrentTimestamp(int $diff = 0): string
    {
        return date('Y-m-d H:i:s', strtotime(sprintf('%+d seconds', $diff)));
    }
}