Repository navigation
Expand file tree
/
Copy pathDatabaseHandler.php
More file actions
117 lines (96 loc) · 2.78 KB
/
Copy pathDatabaseHandler.php
File metadata and controls
117 lines (96 loc) · 2.78 KB
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
109
110
111
112
113
114
115
116
117
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Session\Handler;
use Carbon\Carbon;
use Hyperf\Collection\Arr;
use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\Support\Traits\InteractsWithTime;
use SessionHandlerInterface;
class DatabaseHandler implements SessionHandlerInterface
{
use InteractsWithTime;
public function __construct(protected string $connection, protected string $table, protected int $minutes)
{
}
public function open(string $path, string $name): bool
{
return true;
}
public function close(): bool
{
return true;
}
public function read($id): false|string
{
$session = (object) $this->getQuery()->find($id);
if (isset($session->last_activity)
&& $session->last_activity < Carbon::now()->subMinutes($this->minutes)->getTimestamp()) {
return '';
}
if (isset($session->payload)) {
return base64_decode($session->payload);
}
return '';
}
public function write(string $id, string $data): bool
{
$payload = $this->getDefaultPayload($data);
if ($this->getQuery()->find($id)) {
$this->performUpdate($id, $payload);
} else {
$this->performInsert($id, $payload);
}
return true;
}
public function destroy(string $id): bool
{
$this->getQuery()->where('id', $id)->delete();
return true;
}
public function gc(int $max_lifetime): false|int
{
return $this->getQuery()
->where('last_activity', '<=', $this->currentTime() - $max_lifetime)
->delete();
}
/**
* Perform an insert operation on the session ID.
*/
protected function performInsert(string $sessionId, array $payload): bool
{
return $this->getQuery()->insert(Arr::set($payload, 'id', $sessionId));
}
/**
* Perform an update operation on the session ID.
*/
protected function performUpdate(string $sessionId, array $payload): int
{
return $this->getQuery()->where('id', $sessionId)->update($payload);
}
/**
* Get the default payload for the session.
*/
protected function getDefaultPayload(string $data): array
{
return [
'payload' => base64_encode($data),
'last_activity' => $this->currentTime(),
];
}
/**
* Get a fresh query builder instance for the table.
*/
protected function getQuery(): Builder
{
return Db::connection($this->connection)->table($this->table);
}
}