From 22b1818b931910c7521b29f89dbb825e3b8d0e64 Mon Sep 17 00:00:00 2001 From: Christopher Hertel Date: Sat, 22 Aug 2026 04:00:09 +0200 Subject: [PATCH] [Server] Stop Session::forget() from creating missing segments --- src/Server/Session/Session.php | 7 ++----- tests/Unit/Server/Session/SessionTest.php | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/Server/Session/Session.php b/src/Server/Session/Session.php index 6eee72d1..4db11f71 100644 --- a/src/Server/Session/Session.php +++ b/src/Server/Session/Session.php @@ -110,15 +110,12 @@ public function forget(string $key): void while (\count($segments) > 1) { $segment = array_shift($segments); if (!isset($data[$segment]) || !\is_array($data[$segment])) { - $data[$segment] = []; + return; } $data = &$data[$segment]; } - $lastKey = array_shift($segments); - if (isset($data[$lastKey])) { - unset($data[$lastKey]); - } + unset($data[array_shift($segments)]); } public function clear(): void diff --git a/tests/Unit/Server/Session/SessionTest.php b/tests/Unit/Server/Session/SessionTest.php index 40483d3d..a6b1697d 100644 --- a/tests/Unit/Server/Session/SessionTest.php +++ b/tests/Unit/Server/Session/SessionTest.php @@ -245,6 +245,21 @@ public function testForgetDoesNotThrowWhenKeyDoesNotExist(): void $this->assertFalse($this->session->has('nonexistent')); } + public function testForgetDoesNotCreateIntermediateSegments(): void + { + $this->session->forget('a.b'); + + $this->assertSame([], $this->session->all()); + } + + public function testForgetDoesNotOverwriteNonArrayIntermediateValue(): void + { + $this->session->set('key', 'string_value'); + $this->session->forget('key.nested'); + + $this->assertSame('string_value', $this->session->get('key')); + } + public function testSessionCanStoreVariousDataTypes(): void { $this->session->set('string', 'value');