-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRedisHandler.php
More file actions
222 lines (187 loc) · 5.21 KB
/
RedisHandler.php
File metadata and controls
222 lines (187 loc) · 5.21 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<?php
namespace Gt\Session;
use Redis;
use RuntimeException;
class RedisHandler extends Handler {
private const DEFAULT_PORT = 6379;
private const DEFAULT_PREFIX_SEPARATOR = ":";
private ?Redis $client = null;
private string $prefix = "";
private int $ttl = 0;
public function open(string $savePath, string $name):bool {
$config = $this->parseSavePath($savePath, $name);
$client = $this->createClient();
$connected = $client->connect(
$config["host"],
$config["port"],
$config["timeout"],
$config["persistentId"],
0,
$config["readTimeout"],
$config["context"],
);
if(!$connected) {
return false;
}
if($config["auth"] !== null && !$client->auth($config["auth"])) {
return false;
}
if($config["database"] > 0 && !$client->select($config["database"])) {
return false;
}
$this->client = $client;
$this->prefix = $config["prefix"];
$this->ttl = $config["ttl"];
return true;
}
public function close():bool {
if(is_null($this->client)) {
return true;
}
return $this->client->close();
}
public function read(string $sessionId):string {
$value = $this->requireClient()->get($this->getKey($sessionId));
return is_string($value) ? $value : "";
}
public function write(string $sessionId, string $sessionData):bool {
$client = $this->requireClient();
$key = $this->getKey($sessionId);
if($this->ttl > 0) {
return $client->setEx($key, $this->ttl, $sessionData);
}
return $client->set($key, $sessionData);
}
public function destroy(string $id = ""):bool {
return $this->requireClient()->del($this->getKey($id)) >= 0;
}
// phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
public function gc(int $maxLifeTime):int|false {
return 0;
}
// phpcs:enable
/**
* @return array{
* host:string,
* port:int,
* timeout:float,
* readTimeout:float,
* persistentId:?string,
* prefix:string,
* ttl:int,
* database:int,
* auth:array{string,string}|string|null,
* context:array{stream:array{verify_peer:bool,verify_peer_name:bool}}|null
* }
*/
private function parseSavePath(string $savePath, string $name):array {
$parts = parse_url($savePath);
if($parts === false || !isset($parts["host"])) {
throw new RuntimeException("Invalid Redis save_path DSN.");
}
parse_str($parts["query"] ?? "", $query);
[$host, $context] = $this->parseHostAndContext($parts, $query);
return [
"host" => $host,
"port" => (int)($parts["port"] ?? self::DEFAULT_PORT),
"timeout" => (float)($query["timeout"] ?? 0),
"readTimeout" => (float)($query["read_timeout"] ?? 0),
"persistentId" => $this->parsePersistentId($query),
"prefix" => $this->parsePrefix($query, $name),
"ttl" => (int)($query["ttl"] ?? ini_get("session.gc_maxlifetime")),
"database" => $this->parseDatabase($parts),
"auth" => $this->parseAuth($parts),
"context" => $context,
];
}
/**
* @param array<string,mixed> $parts
* @param array<string,mixed> $query
* @return array{
* 0:string,
* 1:array{stream:array{verify_peer:bool,verify_peer_name:bool}}|null
* }
*/
private function parseHostAndContext(array $parts, array $query):array {
$scheme = strtolower($parts["scheme"] ?? "redis");
$host = $parts["host"];
if(!in_array($scheme, ["rediss", "tls"], true)) {
return [$host, null];
}
return [
"tls://$host",
[
"stream" => [
"verify_peer" => filter_var(
$query["verify_peer"] ?? true,
FILTER_VALIDATE_BOOL
),
"verify_peer_name" => filter_var(
$query["verify_peer_name"] ?? true,
FILTER_VALIDATE_BOOL
),
],
],
];
}
/**
* @param array<string,mixed> $parts
* @return array{string,string}|string|null
*/
private function parseAuth(array $parts):array|string|null {
if(isset($parts["user"]) && $parts["user"] !== "" && isset($parts["pass"])) {
return [rawurldecode($parts["user"]), rawurldecode($parts["pass"])];
}
if(isset($parts["pass"])) {
return rawurldecode($parts["pass"]);
}
return null;
}
/**
* @param array<string,mixed> $query
*/
private function parsePersistentId(array $query):?string {
if(
!isset($query["persistent"])
|| !filter_var($query["persistent"], FILTER_VALIDATE_BOOL)
) {
return null;
}
return is_string($query["persistent_id"] ?? null)
? $query["persistent_id"]
: "phpgt-session";
}
/**
* @param array<string,mixed> $query
*/
private function parsePrefix(array $query, string $name):string {
return is_string($query["prefix"] ?? null)
? $query["prefix"]
: $name . self::DEFAULT_PREFIX_SEPARATOR;
}
/**
* @param array<string,mixed> $parts
*/
private function parseDatabase(array $parts):int {
return isset($parts["path"])
? (int)trim($parts["path"], "/")
: 0;
}
private function getKey(string $sessionId):string {
return $this->prefix . $sessionId;
}
protected function createClient():Redis {
if(!class_exists(Redis::class)) {
throw new RuntimeException(
"The phpredis extension is required to use Gt\\Session\\RedisHandler."
);
}
return new Redis();
}
private function requireClient():Redis {
if(is_null($this->client)) {
throw new RuntimeException("RedisHandler::open() must be called before use.");
}
return $this->client;
}
}