8000 Deprecat service "session" · symfony/symfony@79d1158 · GitHub
[go: up one dir, main page]

Skip to content

Commit 79d1158

Browse files
committed
Deprecat service "session"
1 parent fdf9a43 commit 79d1158

File tree

20 files changed

+256
-40
lines changed

20 files changed

+256
-40
lines changed

UPGRADE-5.2.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ FrameworkBundle
1616
used to be added by default to the seed, which is not the case anymore. This allows sharing caches between
1717
apps or different environments.
1818
* Deprecated the `lock.RESOURCE_NAME` and `lock.RESOURCE_NAME.store` services and the `lock`, `LockInterface`, `lock.store` and `PersistingStoreInterface` aliases, use `lock.RESOURCE_NAME.factory`, `lock.factory` or `LockFactory` instead.
19+
* Deprecated the `session` service and the `SessionInterface` alias, use the `Request::getSession()` or the new `RequestStack::getSession()` methods instead.
1920

2021
Form
2122
----
@@ -125,3 +126,4 @@ Security
125126
`AbstractRememberMeServices::$firewallName`, the old property will be removed
126127
in 6.0.
127128

129+
* The `$session` constructor argument of `SessionTokenStorage` has been deprecated and replaced by the `$requestStack` one which expects an `RequestStack`.

UPGRADE-6.0.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ FrameworkBundle
5959
* The `form.factory`, `form.type.file`, `translator`, `security.csrf.token_manager`, `serializer`,
6060
`cache_clearer`, `filesystem` and `validator` services are now private.
6161
* Removed the `lock.RESOURCE_NAME` and `lock.RESOURCE_NAME.store` services and the `lock`, `LockInterface`, `lock.store` and `PersistingStoreInterface` aliases, use `lock.RESOURCE_NAME.factory`, `lock.factory` or `LockFactory` instead.
62+
* Removed the `session` service and the `SessionInterface` alias, use the `Request::getSession()` or the new `RequestStack::getSession()` methods instead.
6263

6364
HttpFoundation
6465
--------------
@@ -151,6 +152,7 @@ Security
151152
in `PreAuthenticatedToken`, `RememberMeToken`, `SwitchUserToken`, `UsernamePasswordToken`,
152153
`DefaultAuthenticationSuccessHandler`.
153154
* Removed the `AbstractRememberMeServices::$providerKey` property in favor of `AbstractRememberMeServices::$firewallName`
155+
* The `$session` constructor argument of `SessionTokenStorage` has been replaced by the `$requestStack` one which expects an `RequestStack` instead.
154156

155157
TwigBundle
156158
----------

src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ CHANGELOG
1515
* added `assertFormValue()` and `assertNoFormValue()` in `WebTestCase`
1616
* Added "--as-tree=3" option to `translation:update` command to dump messages as a tree-like structure. The given value defines the level where to switch to inline YAML
1717
* Deprecated the `lock.RESOURCE_NAME` and `lock.RESOURCE_NAME.store` services and the `lock`, `LockInterface`, `lock.store` and `PersistingStoreInterface` aliases, use `lock.RESOURCE_NAME.factory`, `lock.factory` or `LockFactory` instead.
18+
* Deprecated the `session` service and the `SessionInterface` alias, use the `Request::getSession()` or the new `RequestStack::getSession()` methods instead.
1819

1920
5.1.0
2021
-----

src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php

+11Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ public static function getSubscribedServices()
9292
'request_stack' => '?'.RequestStack::class,
9393
'http_kernel' => '?'.HttpKernelInterface::class,
9494
'serializer' => '?'.SerializerInterface::class,
95-
'session' => '?'.SessionInterface::class,
95+
'session' => '?sessionDeprecatedDoNotUse',
9696
'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class,
9797
'twig' => '?'.Environment::class,
9898
'doctrine' => '?'.ManagerRegistry::class,
@@ -199,11 +199,19 @@ protected function file($file, string $fileName = null, string $disposition = Re
199199
*/
200200
protected function addFlash(string $type, $message): void
201201
{
202-
if (!$this->container->has('session')) {
202+
// BC for symfony/http-foundation < 5.2
203+
if (method_exists($requestStack = $this->container->get('request_stack'), 'getSession')) {
204+
$session = $requestStack->getSession();
205+
} elseif ((null !== $request = $requestStack->getCurrentRequest()) && $request->hasSession()) {
206+
$session = $request->getSession();
207+
} else {
208+
$session = null;
209+
}
210+
if (null === $session) {
203211
throw new \LogicException('You can not use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".');
204212
}
205213

206-
$this->container->get('session')->getFlashBag()->add($type, $message);
214+
$session->getFlashBag()->add($type, $message);
207215
}
208216

209217
/**

src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/SessionPass.php

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,29 @@ class SessionPass implements CompilerPassInterface
2222
{
2323
public function process(ContainerBuilder $container)
2424
{
25-
if (!$container->hasDefinition('session')) {
25+
if (!$container->has('session')) {
2626
return;
2727
}
2828

29+
// BC layer: When user overrides the `session` service it's not an alias anymore.
30+
if ($container->hasDefinition('session')) {
31+
$definition = $container->getDefinition('session');
32+
$definition->setDeprecated('symfony/framework-bundle', '5.2', 'The "%service_id%" service is deprecated, use "$requestStack->getSession()" instead.');
33+
34+
// Given `session` is not an alias to `.session.do-not-use` anymore,
35+
// we make `.session.do-not-use` an alias of `session`.
36+
$container->removeDefinition('.session.do-not-use');
37+
$container->setAlias('.session.do-not-use', 'session');
38+
} else {
39+
$definition = $container->getDefinition('.session.do-not-use');
40+
}
41+
2942
$bags = [
3043
'session.flash_bag' => $container->hasDefinition('session.flash_bag') ? $container->getDefinition('session.flash_bag') : null,
3144
'session.attribute_bag' => $container->hasDefinition('session.attribute_bag') ? $container->getDefinition('session.attribute_bag') : null,
3245
];
3346

34-
foreach ($container->getDefinition('session')->getArguments() as $v) {
47+
foreach ($definition->getArguments() as $v) {
3548
if (!$v instanceof Reference || !isset($bags[$bag = (string) $v]) || !\is_array($factory = $bags[$bag]->getFactory())) {
3649
continue;
3750
}

src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@
135135
use Symfony\Component\Routing\Loader\AnnotationFileLoader;
136136
use Symfony\Component\Security\Core\Security;
137137
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
138+
use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;
138139
use Symfony\Component\Serializer\Encoder\DecoderInterface;
139140
use Symfony\Component\Serializer\Encoder\EncoderInterface;
140141
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
@@ -1531,6 +1532,12 @@ private function registerSecurityCsrfConfiguration(array $config, ContainerBuild
15311532
// Enable services for CSRF protection (even without forms)
15321533
$loader->load('security_csrf.php');
15331534

1535+
// BC for symfony/security-core < 5.2
1536+
if (!(new \ReflectionClass(SessionTokenStorage::class))->hasMethod('getSession')) {
1537+
$container->getDefinition('security.csrf.token_storage')
1538+
->setArgument(0, new Reference('session'));
1539+
}
1540+
15341541
if (!class_exists(CsrfExtension::class)) {
15351542
$container->removeDefinition('twig.extension.security_csrf');
15361543
}

src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,17 @@ public function loginUser($user, string $firewallContext = 'main'): self
122122

123123
$token = new TestBrowserToken($user->getRoles(), $user);
124124
$token->setAuthenticated(true);
125-
$session = $this->getContainer()->get('session');
125+
// BC for symfony/http-foundation < 5.2
126+
if (method_exists($requestStack = $this->getContainer()->get('request_stack'), 'getSession')) {
127+
$session = $requestStack->getSession();
128+
} elseif ((null !== $request = $requestStack->getCurrentRequest()) && $request->hasSession()) {
129+
$session = $request->getSession();
130+
} else {
131+
$session = null;
132+
}
133+
if (null === $session) {
134+
throw new \LogicException('Unable to find a session.');
135+
}
126136
$session->set('_security_'.$firewallContext, serialize($token));
127137
$session->save();
128138

src/Symfony/Bundle/FrameworkBundle/Resources/config/security_csrf.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
->alias(TokenGeneratorInterface::class, 'security.csrf.token_generator')
2828

2929
->set('security.csrf.token_storage', SessionTokenStorage::class)
30-
->args([service('session')])
30+
->args([service('request_stack')])
3131

3232
->alias(TokenStorageInterface::class, 'security.csrf.token_storage')
3333

src/Symfony/Bundle/FrameworkBundle/Resources/config/session.php

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
1313

14+
use Symfony\Bundle\FrameworkBundle\Session\DeprecatedSessionFactory;
1415
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
1516
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
1617
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
@@ -33,15 +34,20 @@
3334
$container->parameters()->set('session.metadata.storage_key', '_sf2_meta');
3435

3536
$container->services()
36-
->set('session', Session::class)
37-
->public()
37+
->set('.session.do-not-use', Session::class) // to be removed in 6.0
3838
->args([
3939
service('session.storage'),
4040
null, // AttributeBagInterface
4141
null, // FlashBagInterface
4242
[service('session_listener'), 'onSessionUsage'],
4343
])
44-
->alias(SessionInterface::class, 'session')
44+
->set('sessionDeprecatedDoNotUse', SessionInterface::class) // to be removed in 6.0
45+
->factory([inline_service(DeprecatedSessionFactory::class)->args([service('request_stack')]), 'getSession'])
46+
->alias('session', '.session.do-not-use')
47+
->public()
48+
->deprecate('symfony/framework-bundle', '5.2', 'The "%alias_id%" alias is deprecated, use "$requestStack->getSession()" instead.')
49+
->alias(SessionInterface::class, '.session.do-not-use')
50+
->deprecate('symfony/framework-bundle', '5.2', 'The "%alias_id%" alias is deprecated, use "$requestStack->getSession()" instead.')
4551
->alias(SessionStorageInterface::class, 'session.storage')
4652
->alias(\SessionHandlerInterface::class, 'session.handler')
4753

@@ -65,12 +71,12 @@
6571
])
6672

6773
->set('session.flash_bag', FlashBag::class)
68-
->factory([service('session'), 'getFlashBag'])
74+
->factory([service('.session.do-not-use'), 'getFlashBag'])
6975
->deprecate('symfony/framework-bundle', '5.1', 'The "%service_id%" service is deprecated, use "$session->getFlashBag()" instead.')
7076
->alias(FlashBagInterface::class, 'session.flash_bag')
7177

7278
->set('session.attribute_bag', AttributeBag::class)
73-
->factory([service('session'), 'getBag'])
79+
->factory([service('.session.do-not-use'), 'getBag'])
7480
->args(['attributes'])
7581
->deprecate('symfony/framework-bundle', '5.1', 'The "%service_id%" service is deprecated, use "$session->getAttributeBag()" instead.')
7682

@@ -94,8 +100,8 @@
94100
->set('session_listener', SessionListener::class)
95101
->args([
96102
service_locator([
97-
'session' => service('session')->ignoreOnInvalid(),
98-
'initialized_session' => service('session')->ignoreOnUninitialized(),
103+
'session' => service('.session.do-not-use')->ignoreOnInvalid(),
104+
'initialized_session' => service('.session.do-not-use')->ignoreOnUninitialized(),
99105
'logger' => service('logger')->ignoreOnInvalid(),
100106
'session_collector' => service('data_collector.request.session_collector')->ignoreOnInvalid(),
101107
]),
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
namespace Symfony\Bundle\FrameworkBundle\Session;
4+
5+
use Symfony\Component\HttpFoundation\RequestStack;
6+
use Symfony\Component\HttpFoundation\Session\SessionInterface;
7+
8+
/**
9+
* Provides session and trigger deprecation.
10+
* Used by service that should trigger deprecation when accessed by user
11+
*
12+
* @author Jérémy Derussé <jeremy@derusse.com>
13+
* @internal to be removed in 6.0
14+
*/
15+
class DeprecatedSessionFactory
16+
{
17+
private $requestStack;
18+
19+
public function __construct(RequestStack $requestStack)
20+
{
21+
$this->requestStack = $requestStack;
22+
}
23+
24+
public function getSession(): ?SessionInterface
25+
{
26+
trigger_deprecation('symfony/framework-bundle', '5.1', 'The "session" service is deprecated, use "$requestStack->getSession()" instead.');
27+
28+
// BC for symfony/http-foundation < 5.2
29+
if (method_exists($this->requestStack, 'getSession')) {
30+
return $this->requestStack->getSession();
31+
}
32+
if ((null !== $request = $this->requestStack->getCurrentRequest()) && $request->hasSession()) {
33+
return $request->getSession();
34+
}
35+
36+
return null;
37+
}
38+
}

src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/RegisterTokenUsageTrackingPass.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public function process(ContainerBuilder $container)
4141
TokenStorageInterface::class => new BoundArgument(new Reference('security.untracked_token_storage'), false),
4242
]);
4343

44-
if (!$container->has('session')) {
44+
if (!$container->has('session.storage')) {
4545
$container->setAlias('security.token_storage', 'security.untracked_token_storage')->setPublic(true);
4646
$container->getDefinition('security.untracked_token_storage')->addTag('kernel.reset', ['method' => 'reset']);
4747
} elseif ($container->hasDefinition('security.context_listener')) {
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler;
13+
14+
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
15+
use Symfony\Component\DependencyInjection\ContainerBuilder;
16+
use Symfony\Component\DependencyInjection\Reference;
17+
18+
/**
19+
* Replace deprecated `session` service in "security.token_storage"
20+
* when UsageTrackingTokenStorage is able to fetch Session from RequestStack.
21+
*
22+
* @author jérémy Derussé <jeremy@derusse.com>
23+
*
24+
* @internal to be removed in 6.0
25+
*/
26+
class SessionPass implements CompilerPassInterface
27+
{
28+
public function process(ContainerBuilder $container)
29+
{
30+
if (!$container->hasDefinition('security.token_storage')) {
31+
return;
32+
}
33+
34+
$definition = $container->getDefinition('security.token_storage');
35+
if ((new \ReflectionClass($definition->getClass()))->hasMethod('getSession')) {
36+
return;
37+
}
38+
39+
$locator = $definition->getArgument(1);
40+
$values = $locator->getValues();
41+
unset($values['request_stack']);
42+
$values['session'] = new Reference('session');
43+
$locator->setValues($values);
44+
}
45+
}

src/Symfony/Bundle/SecurityBundle/Resources/config/security.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@
7474
->args([
7575
service('security.untracked_token_storage'),
7676
service_locator([
77-
'session' => service('session'),
77+
'request_stack' => service('request_stack'),
7878
]),
7979
])
8080
->tag('kernel.reset', ['method' => 'disableUsageTracking'])

src/Symfony/Bundle/SecurityBundle/SecurityBundle.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\RegisterGlobalSecurityEventListenersPass;
1919
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\RegisterLdapLocatorPass;
2020
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\RegisterTokenUsageTrackingPass;
21+
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\SessionPass;
2122
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\SortFirewallListenersPass;
2223
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AnonymousFactory;
2324
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\CustomAuthenticatorFactory;
@@ -81,6 +82,7 @@ public function build(ContainerBuilder $container)
8182
$container->addCompilerPass(new RegisterGlobalSecurityEventListenersPass(), PassConfig::TYPE_BEFORE_REMOVING, -200);
8283
// execute after ResolveChildDefinitionsPass optimization pass, to ensure class names are set
8384
$container->addCompilerPass(new SortFirewallListenersPass(), PassConfig::TYPE_BEFORE_REMOVING);
85+
$container->addCompilerPass(new SessionPass());
8486

8587
$container->addCompilerPass(new AddEventAliasesPass(array_merge(
8688
AuthenticationEvents::ALIASES,

src/Symfony/Component/HttpFoundation/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ CHANGELOG
1010
* added ability to use comma separated ip addresses for `RequestMatcher::matchIps()`
1111
* added `Request::toArray()` to parse a JSON request body to an array
< 341A /td>
1212
* added `RateLimiter\RequestRateLimiterInterface` and `RateLimiter\AbstractRequestRateLimiter`
13+
* added `RequestStack::getSession` method.
1314

1415
5.1.0
1516
-----

src/Symfony/Component/HttpFoundation/RequestStack.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
namespace Symfony\Component\HttpFoundation;
1313

14+
use Symfony\Component\HttpFoundation\Session\SessionInterface;
15+
1416
/**
1517
* Request stack that controls the lifecycle of requests.
1618
*
@@ -100,4 +102,16 @@ public function getParentRequest()
100102

101103
return $this->requests[$pos];
102104
}
105+
106+
/**
107+
* Gets the current session.
108+
*/
109+
public function getSession(): ?SessionInterface
110+
{
111+
if (null === $request = end($this->requests) ?: null) {
112+
return null;
113+
}
114+
115+
return $request->hasSession() ? $request->getSession() : null;
116+
}
103117
}

src/Symfony/Component/HttpKernel/EventListener/AbstractSessionListener.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,10 @@ public function onKernelRequest(RequestEvent $event)
6161
if ($request->hasSession()) {
6262
// no-op
6363
} elseif (method_exists($request, 'setSessionFactory')) {
64-
$request->setSessionFactory(function () { return $this->getSession(); });
64+
$sess = null;
65+
$request->setSessionFactory(function () use (&$sess) {
66+
return $sess ?? $sess = $this->getSession();
67+
});
6568
} elseif ($session = $this->getSession()) {
6669
$request->setSession($session);
6770
}

src/Symfony/Component/Security/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ CHANGELOG
1414
* Added a CurrentUser attribute to force the UserValueResolver to resolve an argument to the current user.
1515
* Added `LoginThrottlingListener`.
1616
* Added `LoginLinkAuthenticator`.
17+
* Deprecated passing a `SessionInterface` to `SessionTokenStorage`, inject a `RequestStack` instead.
1718

1819
5.1.0
1920
-----

0 commit comments

Comments
 (0)
0