Skip to content

Commit 8aca41a

Browse files
authored
Always call onBeforeDataWrite handlers, even if the session data does not change (#15)
This way, the handler may change the session data, and set additionalData too. This was documented as possible even before, but in reality setting additional data didn't really always store them to the sessions table. That's because nothing was written to the table when session data hasn't changed, no matter what was in additionalData. And setting additionalData in the handler did mostly nothing, because the handler was called only when there was a change in the session data aka the Catch-22 problem. If anyone would need the handler to be executed only when session data has changed, this could be emulated by passing the result of `$this->data[$id] !== $data` as a param to the handler, and then adding an `if` in the handler.
2 parents d465284 + b1f7667 commit 8aca41a

File tree

2 files changed

+3
-4
lines changed

2 files changed

+3
-4
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ Migration from unecrypted to encrypted session storage is not (yet?) supported.
7373
## Events
7474

7575
### `onBeforeDataWrite`
76-
The event occurs before session data is written to the session table, both for a new session (when a new row is inserted) or an existing session (a row us updated). The event is not triggered when just the session timestamp is updated without any change in the session data.
76+
The event occurs before session data is written to the session table, both for a new session (when a new row is inserted) or an existing session (a row is updated), even if there's no change in the session data.
7777

7878
You can add a new column by calling `setAdditionalData()` in the event handler:
7979
```

src/MysqlSessionHandler.php

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,12 +160,11 @@ public function write(string $id, string $data): bool
160160
$this->lock();
161161
$hashedSessionId = $this->hash($id);
162162
$time = \time();
163-
164-
if (!isset($this->data[$id]) || $this->data[$id] !== $data) {
163+
$this->onBeforeDataWrite();
164+
if (!isset($this->data[$id]) || $this->data[$id] !== $data || $this->additionalData !== []) {
165165
if ($this->encryptionService) {
166166
$data = $this->encryptionService->encrypt($data);
167167
}
168-
$this->onBeforeDataWrite();
169168
$row = $this->explorer->table($this->tableName)->get($hashedSessionId);
170169
if ($row) {
171170
$row->update([

0 commit comments

Comments
 (0)