From 6ce98052e3c594a145d261b2b9490d4efbe5a3b8 Mon Sep 17 00:00:00 2001 From: Federkun Date: Tue, 11 Sep 2018 00:19:45 +0100 Subject: [PATCH] Use `session.cookie_lifetime` value when creating the session cookie. --- src/PhpSessionPersistence.php | 4 +++ test/PhpSessionPersistenceTest.php | 41 ++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/PhpSessionPersistence.php b/src/PhpSessionPersistence.php index 91b7783..7db2365 100644 --- a/src/PhpSessionPersistence.php +++ b/src/PhpSessionPersistence.php @@ -115,6 +115,10 @@ public function persistSession(SessionInterface $session, ResponseInterface $res ->withValue($this->cookie) ->withPath(ini_get('session.cookie_path')); + if ($cookieLifetime = (int) ini_get('session.cookie_lifetime')) { + $sessionCookie = $sessionCookie->withExpires(time() + $cookieLifetime); + } + $response = FigResponseCookies::set($response, $sessionCookie); if (! $this->cacheLimiter || $this->responseAlreadyHasCacheHeaders($response)) { diff --git a/test/PhpSessionPersistenceTest.php b/test/PhpSessionPersistenceTest.php index 04cdd8a..aa41739 100644 --- a/test/PhpSessionPersistenceTest.php +++ b/test/PhpSessionPersistenceTest.php @@ -442,4 +442,45 @@ public function testCookiesSetWithoutRegenerate() $this->assertNotEmpty($response->getHeaderLine('Set-Cookie')); } + + public function testCookiesSetWithDefaultLifetime() + { + $persistence = new PhpSessionPersistence(); + $request = new ServerRequest(); + $session = $persistence->initializeSessionFromRequest($request); + + $session->set('foo', 'bar'); + + $response = $persistence->persistSession($session, new Response()); + + $setCookie = FigResponseCookies::get($response, session_name()); + + $this->assertNotEmpty($response->getHeaderLine('Set-Cookie')); + $this->assertInstanceOf(SetCookie::class, $setCookie); + $this->assertSame(0, $setCookie->getExpires()); + } + + public function testCookiesSetWithCustomLifetime() + { + $lifetime = 300; + $expectedTimestamp = time() + $lifetime; + + $ini = $this->applyCustomSessionOptions([ + 'cookie_lifetime' => $lifetime, + ]); + + $persistence = new PhpSessionPersistence(); + $request = new ServerRequest(); + $session = $persistence->initializeSessionFromRequest($request); + + $session->set('foo', 'bar'); + + $response = $persistence->persistSession($session, new Response()); + + $setCookie = FigResponseCookies::get($response, session_name()); + $this->assertInstanceOf(SetCookie::class, $setCookie); + $this->assertSame($expectedTimestamp, $setCookie->getExpires()); + + $this->restoreOriginalSessionIniSettings($ini); + } }