diff --git a/src/Storageless/Http/SessionMiddleware.php b/src/Storageless/Http/SessionMiddleware.php index 7b8fb2f9..64e9972c 100644 --- a/src/Storageless/Http/SessionMiddleware.php +++ b/src/Storageless/Http/SessionMiddleware.php @@ -58,12 +58,14 @@ final class SessionMiddleware implements MiddlewareInterface private Configuration $config; private SetCookie $defaultCookie; + /** @param literal-string $sessionAttribute */ public function __construct( Configuration $configuration, SetCookie $defaultCookie, private int $idleTimeout, private Clock $clock, private int $refreshTime = self::DEFAULT_REFRESH_TIME, + private string $sessionAttribute = self::SESSION_ATTRIBUTE, ) { $this->config = $configuration; $this->defaultCookie = clone $defaultCookie; @@ -130,7 +132,7 @@ public function process(Request $request, RequestHandlerInterface $handler): Res return $this->appendToken( $sessionContainer, - $handler->handle($request->withAttribute(self::SESSION_ATTRIBUTE, $sessionContainer)), + $handler->handle($request->withAttribute($this->sessionAttribute, $sessionContainer)), $token, ); } diff --git a/test/StoragelessTest/Http/SessionMiddlewareTest.php b/test/StoragelessTest/Http/SessionMiddlewareTest.php index 2a3a4cc6..5dbb6abb 100644 --- a/test/StoragelessTest/Http/SessionMiddlewareTest.php +++ b/test/StoragelessTest/Http/SessionMiddlewareTest.php @@ -735,6 +735,34 @@ public function testMutableCookieWillNotBeUsed(): void ); } + public function testAllowCustomRequestAttributeName(): void + { + $customAttributeName = 'my_custom_session_attribute_name'; + self::assertNotEmpty($customAttributeName); + + $middleware = new SessionMiddleware( + Configuration::forSymmetricSigner( + new Sha256(), + self::makeRandomSymmetricKey(), + ), + SetCookie::create(SessionMiddleware::DEFAULT_COOKIE), + 100, + SystemClock::fromSystemTimezone(), + 100, + $customAttributeName, + ); + + $middleware->process( + new ServerRequest(), + $this->fakeDelegate(static function (ServerRequestInterface $request) use ($customAttributeName) { + self::assertInstanceOf(SessionInterface::class, $request->getAttribute($customAttributeName)); + self::assertNull($request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE)); + + return new Response(); + }), + ); + } + private function ensureSameResponse( SessionMiddleware $middleware, ServerRequestInterface $request,