Description
Description
When a request is flagged as stateless, we're not supposed to use the session.
Still, this was often forgotten and I saw many fixes in Symfony codebase like
#57372
#54742
#51350
I think there is something to improve in other to have easier stateless check and/or integrate the check inside hasSession/getSession
.
First, to me, the _attribute
seems internal to Symfony and it's not perfect to ask the user to check for
$request->attributes->getBoolean('_stateless')
so I would propose to introduce Request::isStateless
which could be done this way 05d4852
Second, since there is an exception/warning checking if the session was used when the request is stateless
cf
what about including the
isStateless
check directly in hasSession
and getSession
method ?
Example
We could have
public function getSession(): SessionInterface
{
if ($this->isStateless()) {
throw new UnexpectedSessionUsageException('Session is used while the request was declared stateless.');
}
$session = $this->session;
if (!$session instanceof SessionInterface && null !== $session) {
$this->setSession($session = $session());
}
if (null === $session) {
throw new SessionNotFoundException('Session has not been set.');
}
return $session;
}
and
- either
hasSession
returns false when the request is stateless. - either
hasSession
returns true and people will have to checkhasSession && !isStateless
to callgetSession
.
Of course, this would be introduced in a BC way with
if ($this->isStateless()) {
trigger_deprecation('symfony/http-foundation', '7.2', 'Accessing the session on a stateless request is deprecated and will throw an exception in next major.');
}
in Symfony 7.
WDYT ? Is there a reason to allowing accessing the session when the request is stateless ?