diff --git a/src/Server/Session/Session.php b/src/Server/Session/Session.php index 66f92941..89e0a251 100644 --- a/src/Server/Session/Session.php +++ b/src/Server/Session/Session.php @@ -31,7 +31,9 @@ class Session implements SessionInterface * * @var array */ - private array $data; + private array $data = []; + + private bool $loaded = false; public function __construct( private SessionStoreInterface $store, @@ -126,6 +128,7 @@ public function forget(string $key): void public function clear(): void { $this->data = []; + $this->loaded = true; } public function pull(string $key, mixed $default = null): mixed @@ -144,6 +147,7 @@ public function all(): array public function hydrate(array $attributes): void { $this->data = $attributes; + $this->loaded = true; } /** @return array */ @@ -157,20 +161,22 @@ public function jsonSerialize(): array */ private function readData(): array { - if (isset($this->data)) { + if ($this->loaded) { return $this->data; } + $this->loaded = true; + $rawData = $this->store->read($this->id); if (false === $rawData) { - return $this->data = []; + return $this->data; } $decoded = json_decode($rawData, true, flags: \JSON_THROW_ON_ERROR); if (!\is_array($decoded)) { - return $this->data = []; + return $this->data; } return $this->data = $decoded; diff --git a/tests/Unit/Server/Session/SessionTest.php b/tests/Unit/Server/Session/SessionTest.php index bd5e94ce..a32d16a4 100644 --- a/tests/Unit/Server/Session/SessionTest.php +++ b/tests/Unit/Server/Session/SessionTest.php @@ -296,6 +296,7 @@ public function testSaveBeforeReadInitializesData() // save() before any get()/set() should not crash $this->assertTrue($session->save()); + $this->assertSame([], $session->all()); } public function testAllReturnsEmptyArrayForNullPayload()