-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSessionData.php
More file actions
369 lines (300 loc) · 11.7 KB
/
Copy pathSessionData.php
File metadata and controls
369 lines (300 loc) · 11.7 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
<?php
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
/**
* Italix Session - SessionData
*
* @package Italix\Session
*/
declare(strict_types=1);
namespace Italix\Session;
/**
* What a session holds, and — more interestingly — how two of them are merged.
*
* PHP's native session **locks**: two requests for the same session are served
* one after the other, so a read-modify-write cannot lose data. The moment the
* store becomes a database or Redis that lock disappears **silently**. Two AJAX
* calls in flight read the same payload, both write it back, and the second
* erases the first. There is no error and no trace; it surfaces months later as
* "the cart occasionally loses an item", and it is the principal defect of
* every hand-rolled session handler.
*
* So this class does not track "the data". It tracks **what this request did to
* the data**, in three buckets, and `reconcile()` replays that intent against
* whatever is in the store at the moment of writing:
*
* - `set()` / `forget()` — wholesale. The caller asserted the whole value;
* last writer wins, which is correct for `set('locale_c', 'it')`.
* - `merge()` — a closure. Re-applied to the *stored* value at write time, so
* two concurrent increments both land.
* - untouched keys — left exactly as the store has them, so a concurrent
* request's unrelated write is not rolled back by this one.
*
* The rule where the two meet, stated because it is the only surprising part: a
* key that has ever been `set()` or `forget()` in this request is written
* wholesale, and any `merge()` on it applies locally only. Once you assert the
* whole value you have taken responsibility for it.
*/
final class SessionData
{
/**
* Reserved key prefix for typed payloads. `set()` refuses it, so an
* application key can never collide with a slot.
*/
public const TYPED_PREFIX = '@type:';
/** @var array<string, mixed> as read from the store at the start of the request */
private array $loaded = [];
/** @var array<string, mixed> the working value of every key this request touched */
private array $writes = [];
/** @var array<string, bool> keys this request removed */
private array $deletes = [];
/** @var array<string, bool> keys written wholesale, i.e. not reconciled */
private array $wholesale = [];
/** @var array<string, array<int, callable>> keys to re-apply against the stored value */
private array $merges = [];
/** @var array<string, SessionPayload|null> hydrated slots, per request */
private array $typed = [];
/** @param array<string, mixed> $values */
public static function from_array(array $values): self
{
$data = new self();
$data->loaded = $values;
return $data;
}
public static function empty(): self
{
return new self();
}
// =========================================================================
// The bag
// =========================================================================
/**
* @param mixed $fallback
* @return mixed
*/
public function get(string $key_c, $fallback = null)
{
if (isset($this->deletes[$key_c])) {
return $fallback;
}
if (array_key_exists($key_c, $this->writes)) {
return $this->writes[$key_c];
}
return array_key_exists($key_c, $this->loaded) ? $this->loaded[$key_c] : $fallback;
}
public function has(string $key_c): bool
{
if (isset($this->deletes[$key_c])) {
return false;
}
return array_key_exists($key_c, $this->writes) || array_key_exists($key_c, $this->loaded);
}
/** @param mixed $value */
public function set(string $key_c, $value): self
{
$this->guard_reserved($key_c);
$this->writes[$key_c] = $value;
$this->wholesale[$key_c] = true;
unset($this->deletes[$key_c], $this->merges[$key_c]);
return $this;
}
/**
* Modify a value with a closure that is replayed against the store.
*
* This is what a structure two requests can touch at once needs. `set()` is
* right for a scalar the caller owns; `merge()` is right for a cart, a
* counter, a list of notifications — anything where "both changes" is the
* correct outcome rather than "whichever finished last".
*
* $data->merge('cart', static function (array $cart) use ($sku_c): array {
* $cart[$sku_c] = ($cart[$sku_c] ?? 0) + 1;
*
* return $cart;
* });
*
* The closure runs twice: once now, so this request reads its own write,
* and once at persist time against the stored value. It must therefore be
* **pure** — no database writes, no mail, no counters outside the value it
* is handed.
*
* @param mixed $default what the closure receives when the key is absent
*/
public function merge(string $key_c, callable $mutator, $default = []): self
{
$this->guard_reserved($key_c);
$this->writes[$key_c] = $mutator($this->get($key_c, $default));
unset($this->deletes[$key_c]);
// A key already written wholesale stays wholesale: the caller asserted
// the value, and silently reopening it for reconciliation would make
// set() mean something different depending on what came after it.
if (!isset($this->wholesale[$key_c])) {
$this->merges[$key_c][] = $mutator;
}
return $this;
}
/**
* Read and remove in one step — what a flash message needs.
*
* @param mixed $fallback
* @return mixed
*/
public function pull(string $key_c, $fallback = null)
{
$value = $this->get($key_c, $fallback);
$this->forget($key_c);
return $value;
}
public function forget(string $key_c): self
{
$this->deletes[$key_c] = true;
$this->wholesale[$key_c] = true;
unset($this->writes[$key_c], $this->merges[$key_c]);
// `ltrim()` takes a character list, not a prefix, so the obvious
// one-liner here would strip an arbitrary set of letters off the class
// name and clear the wrong slot.
if (strpos($key_c, self::TYPED_PREFIX) === 0) {
$this->typed[substr($key_c, strlen(self::TYPED_PREFIX))] = null;
}
return $this;
}
/** Empty the session without ending it — used by `Session::authenticate()` on a privilege change. */
public function clear(): self
{
foreach (array_keys($this->all()) as $key_c) {
$this->deletes[(string) $key_c] = true;
$this->wholesale[(string) $key_c] = true;
}
$this->writes = [];
$this->merges = [];
$this->typed = [];
return $this;
}
/** @return array<string, mixed> the view this request sees */
public function all(): array
{
$values = array_merge($this->loaded, $this->writes);
foreach (array_keys($this->deletes) as $key_c) {
unset($values[$key_c]);
}
return $values;
}
public function is_dirty(): bool
{
return $this->writes !== [] || $this->deletes !== [];
}
// =========================================================================
// Typed slots
// =========================================================================
/**
* Store a typed payload under its own class name.
*
* The slot is the class, so there is exactly one of each per session and no
* key to spell wrong.
*/
public function put(SessionPayload $payload): self
{
$class_c = get_class($payload);
$this->writes[self::TYPED_PREFIX . $class_c] = $payload->to_array();
$this->wholesale[self::TYPED_PREFIX . $class_c] = true;
unset($this->deletes[self::TYPED_PREFIX . $class_c]);
$this->typed[$class_c] = $payload;
return $this;
}
/**
* The payload of that class, or null.
*
* Null when the slot is empty **and** when what is stored no longer
* describes a usable instance — a field renamed between deployments is an
* ordinary event, and the right answer is an empty slot rather than a
* failed request. That decision belongs to the class: see
* `SessionPayload::from_array()`.
*/
public function typed(string $class_c): ?SessionPayload
{
if (array_key_exists($class_c, $this->typed)) {
return $this->typed[$class_c];
}
$stored = $this->get(self::TYPED_PREFIX . $class_c);
if (!is_array($stored) || !is_subclass_of($class_c, SessionPayload::class, true)) {
return $this->typed[$class_c] = null;
}
/** @var callable(array):?SessionPayload $factory */
$factory = [$class_c, 'from_array'];
return $this->typed[$class_c] = $factory($stored);
}
public function forget_typed(string $class_c): self
{
$this->forget(self::TYPED_PREFIX . $class_c);
$this->typed[$class_c] = null;
return $this;
}
// =========================================================================
// Persistence — used by Session::end(), not by application code
// =========================================================================
/**
* This request's intent, replayed against whatever the store holds now.
*
* @param array<string, mixed> $fresh the payload as it stands in the store
* @return array<string, mixed>
*/
public function reconcile(array $fresh): array
{
foreach (array_keys($this->wholesale) as $key_c) {
$key_c = (string) $key_c;
if (isset($this->deletes[$key_c])) {
unset($fresh[$key_c]);
continue;
}
if (array_key_exists($key_c, $this->writes)) {
$fresh[$key_c] = $this->writes[$key_c];
}
}
foreach ($this->merges as $key_c => $mutators) {
$value = array_key_exists($key_c, $fresh) ? $fresh[$key_c] : [];
foreach ($mutators as $mutator) {
$value = $mutator($value);
}
$fresh[$key_c] = $value;
}
return $fresh;
}
/**
* Promote everything this request can see into a wholesale write.
*
* Called on a rotation, where the successor's row is empty: without this,
* the half of the payload nobody touched would be reconciled against
* nothing and silently disappear — which is exactly the guest cart
* vanishing at login that rotation is supposed to prevent.
*/
public function promote_all(): self
{
foreach ($this->all() as $key_c => $value) {
$this->writes[(string) $key_c] = $value;
$this->wholesale[(string) $key_c] = true;
}
// The closures have already been folded into the values above, and
// there is nothing in the new row to reconcile them against.
$this->merges = [];
return $this;
}
/** After a successful write, this request's changes are the baseline. */
public function settle(array $values): void
{
$this->loaded = $values;
$this->writes = [];
$this->deletes = [];
$this->wholesale = [];
$this->merges = [];
}
private function guard_reserved(string $key_c): void
{
if (strpos($key_c, self::TYPED_PREFIX) === 0) {
throw new SessionException(
"\"{$key_c}\" is reserved for typed payloads. Use put() with a SessionPayload instead."
);
}
}
}