Skip to content

Commit

Permalink
Merge pull request #563 from Slamdunk/custom_attribute_name
Browse files Browse the repository at this point in the history
Allow custom session attribute names
  • Loading branch information
Ocramius authored Mar 28, 2023
2 parents 967ffe7 + aae8ed0 commit ee90862
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Storageless/Http/SessionMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
);
}
Expand Down
28 changes: 28 additions & 0 deletions test/StoragelessTest/Http/SessionMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit ee90862

Please sign in to comment.