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

Skip to content

Commit 54acc00

Browse files
committed
Deprecat service "session"
1 parent bf99d8c commit 54acc00

File tree

37 files changed

+431
-77
lines changed

37 files changed

+431
-77
lines changed

UPGRADE-5.3.md

+5
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ Form
2323
* Deprecated passing an array as the second argument of the `RadioListMapper::mapDataToForms()` method, pass `\Traversable` instead
2424
* Deprecated passing an array as the first argument of the `RadioListMapper::mapFormsToData()` method, pass `\Traversable` instead
2525

26+
FrameworkBundle
27+
---------------
28+
29+
* Deprecate the `session` service and the `SessionInterface` alias, use the `\Symfony\Component\HttpFoundation\Request::getSession()` or the new `\Symfony\Component\HttpFoundation\RequestStack::getSession()` methods instead
30+
2631
HttpFoundation
2732
--------------
2833

UPGRADE-6.0.md

+4
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ Form
6969
FrameworkBundle
7070
---------------
7171

72+
* Remove the `session` service and the `SessionInterface` alias, use the `\Symfony\Component\HttpFoundation\Request::getSession()` or the new `\Symfony\Component\HttpFoundation\RequestStack::getSession()` methods instead
7273
* `MicroKernelTrait::configureRoutes()` is now always called with a `RoutingConfigurator`
7374
* The "framework.router.utf8" configuration option defaults to `true`
7475
* Removed `session.attribute_bag` service and `session.flash_bag` service.
@@ -165,6 +166,9 @@ Routing
165166
Security
166167
--------
167168

169+
* Drop support for `SessionInterface $session` as constructor argument of `SessionTokenStorage`, inject a `\Symfony\Component\HttpFoundation\RequestStack $requestStack` instead
170+
* Drop support for `session` provided by the ServiceLocator injected in `UsageTrackingTokenStorage`, provide a `request_stack` service instead
171+
* Make `SessionTokenStorage` throw a `SessionNotFoundException` when called outside a request context
168172
* Removed `ROLE_PREVIOUS_ADMIN` role in favor of `IS_IMPERSONATOR` attribute
169173
* Removed `LogoutSuccessHandlerInterface` and `LogoutHandlerInterface`, register a listener on the `LogoutEvent` event instead.
170174
* Removed `DefaultLogoutSuccessHandler` in favor of `DefaultLogoutListener`.

src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ CHANGELOG
44
5.3
55
---
66

7+
* Deprecate the `session` service and the `SessionInterface` alias, use the `Request::getSession()` or the new `RequestStack::getSession()` methods instead
78
* Added `AbstractController::renderForm()` to render a form and set the appropriate HTTP status code
89
* Added support for configuring PHP error level to log levels
910
* Added the `dispatcher` option to `debug:event-dispatcher`

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

+5-4
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
use Symfony\Component\Form\FormFactoryInterface;
2323
use Symfony\Component\Form\FormInterface;
2424
use Symfony\Component\HttpFoundation\BinaryFileResponse;
25+
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
2526
use Symfony\Component\HttpFoundation\JsonResponse;
2627
use Symfony\Component\HttpFoundation\RedirectResponse;
2728
use Symfony\Component\HttpFoundation\Request;
@@ -200,11 +201,11 @@ protected function file($file, string $fileName = null, string $disposition = Re
200201
*/
201202
protected function addFlash(string $type, $message): void
202203
{
203-
if (!$this->container->has('session')) {
204-
throw new \LogicException('You can not use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".');
204+
try {
205+
$this->container->get('request_stack')->getSession()->getFlashBag()->add($type, $message);
206+
} catch (SessionNotFoundException $e) {
207+
throw new \LogicException('You can not use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".', 0, $e);
205208
}
206-
207-
$this->container->get('session')->getFlashBag()->add($type, $message);
208209
}
209210

210211
/**

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

+23-3
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,41 @@ class SessionPass implements CompilerPassInterface
2222
{
2323
public function process(ContainerBuilder $container)
2424
{
25-
if (!$container->hasDefinition('session')) {
25+
if (!$container->has('session.storage')) {
2626
return;
2727
}
2828

29+
// BC layer: Make "session" an alias of ".session.do-not-use" when not overriden by the user
30+
if (!$container->has('session')) {
31+
$alias = $container->setAlias('session', '.session.do-not-use');
32+
$alias->setDeprecated('symfony/framework-bundle', '5.3', 'The "%alias_id%" service is deprecated, use "$requestStack->getSession()" instead.');
33+
34+
return;
35+
}
36+
37+
if ($container->hasDefinition('session')) {
38+
$definition = $container->getDefinition('session');
39+
$definition->setDeprecated('symfony/framework-bundle', '5.3', 'The "%service_id%" service is deprecated, use "$requestStack->getSession()" instead.');
40+
} else {
41+
$alias = $container->getAlias('session');
42+
$alias->setDeprecated('symfony/framework-bundle', '5.3', 'The "%alias_id%" alias is deprecated, use "$requestStack->getSession()" instead.');
43+
$definition = $container->findDefinition('session');
44+
}
45+
46+
// Convert internal service `.session.do-not-use` into alias of `session`.
47+
$container->setAlias('.session.do-not-use', 'session');
48+
2949
$bags = [
3050
'session.flash_bag' => $container->hasDefinition('session.flash_bag') ? $container->getDefinition('session.flash_bag') : null,
3151
'session.attribute_bag' => $container->hasDefinition('session.attribute_bag') ? $container->getDefinition('session.attribute_bag') : null,
3252
];
3353

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

39-
if ([0, 1] !== array_keys($factory) || !$factory[0] instanceof Reference || 'session' !== (string) $factory[0]) {
59+
if ([0, 1] !== array_keys($factory) || !$factory[0] instanceof Reference || !\in_array((string) $factory[0], ['session', '.session.do-not-use'], true)) {
4060
continue;
4161
}
4262

src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use Symfony\Component\DependencyInjection\ContainerInterface;
1919
use Symfony\Component\HttpFoundation\Request;
2020
use Symfony\Component\HttpFoundation\Response;
21+
use Symfony\Component\HttpFoundation\Session\Session;
2122
use Symfony\Component\HttpKernel\HttpKernelBrowser;
2223
use Symfony\Component\HttpKernel\KernelInterface;
2324
use Symfony\Component\HttpKernel\Profiler\Profile as HttpProfile;
@@ -122,7 +123,7 @@ public function loginUser($user, string $firewallContext = 'main'): self
122123

123124
$token = new TestBrowserToken($user->getRoles(), $user);
124125
$token->setAuthenticated(true);
125-
$session = $this->getContainer()->get('session');
126+
$session = new Session($this->getContainer()->get('test.service_container')->get('session.storage'));
126127
$session->set('_security_'.$firewallContext, serialize($token));
127128
$session->save();
128129

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

+1-1
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

+10-7
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,17 @@
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('.session.deprecated', SessionInterface::class) // to be removed in 6.0
45+
->factory([inline_service(DeprecatedSessionFactory::class)->args([service('request_stack')]), 'getSession'])
46+
->alias(SessionInterface::class, '.session.do-not-use')
47+
->deprecate('symfony/framework-bundle', '5.3', 'The "%alias_id%" alias is deprecated, use "$requestStack->getSession()" instead.')
4548
->alias(SessionStorageInterface::class, 'session.storage')
4649
->alias(\SessionHandlerInterface::class, 'session.handler')
4750

@@ -65,12 +68,12 @@
6568
])
6669

6770
->set('session.flash_bag', FlashBag::class)
68-
->factory([service('session'), 'getFlashBag'])
71+
->factory([service('.session.do-not-use'), 'getFlashBag'])
6972
->deprecate('symfony/framework-bundle', '5.1', 'The "%service_id%" service is deprecated, use "$session->getFlashBag()" instead.')
7073
->alias(FlashBagInterface::class, 'session.flash_bag')
7174

7275
->set('session.attribute_bag', AttributeBag::class)
73-
->factory([service('session'), 'getBag'])
76+
->factory([service('.session.do-not-use'), 'getBag'])
D7AE
7477
->args(['attributes'])
7578
->deprecate('symfony/framework-bundle', '5.1', 'The "%service_id%" service is deprecated, use "$session->getAttributeBag()" instead.')
7679

@@ -94,8 +97,8 @@
9497
->set('session_listener', SessionListener::class)
9598
->args([
9699
service_locator([
97-
'session' => service('session')->ignoreOnInvalid(),
98-
'initialized_session' => service('session')->ignoreOnUninitialized(),
100+
'session' => service('.session.do-not-use')->ignoreOnInvalid(),
101+
'initialized_session' => service('.session.do-not-use')->ignoreOnUninitialized(),
99102
'logger' => service('logger')->ignoreOnInvalid(),
100103
'session_collector' => service('data_collector.request.session_collector')->ignoreOnInvalid(),
101104
]),

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
->set('test.session.listener', TestSessionListener::class)
3939
->args([
4040
service_locator([
41-
'session' => service('session')->ignoreOnInvalid(),
41+
'session' => service('.session.do-not-use')->ignoreOnInvalid(),
4242
]),
4343
])
4444
->tag('kernel.event_subscriber')
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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\FrameworkBundle\Session;
13+
14+
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
15+
use Symfony\Component\HttpFoundation\RequestStack;
16+
use Symfony\Component\HttpFoundation\Session\SessionInterface;
17+
18+
/**
19+
* Provides session and trigger deprecation.
20+
*
21+
* Used by service that should trigger deprecation when accessed by the user.
22+
*
23+
* @author Jérémy Derussé <jeremy@derusse.com>
24+
*
25+
* @internal to be removed in 6.0
26+
*/
27+
class DeprecatedSessionFactory
28+
{
29+
private $requestStack;
30+
31+
public function __construct(RequestStack $requestStack)
32+
{
33+
$this->requestStack = $requestStack;
34+
}
35+
36+
public function getSession(): ?SessionInterface
37+
{
38+
trigger_deprecation('symfony/framework-bundle', '5.3', 'The "session" service is deprecated, use "$requestStack->getSession()" instead.');
39+
40+
try {
41+
return $this->requestStack->getSession();
42+
} catch (SessionNotFoundException $e) {
43+
return null;
44+
}
45+
}
46+
}

src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php

+6
Original file line numberDiff line numberDiff line change
@@ -497,8 +497,14 @@ public function testAddFlash()
497497
$session = $this->createMock(Session::class);
498498
$session->expects($this->once())->method('getFlashBag')->willReturn($flashBag);
499499

500+
$request = new Request();
501+
$request->setSession($session);
502+
$requestStack = new RequestStack();
503+
$requestStack->push($request);
504+
500505
$container = new Container();
501506
$container->set('session', $session);
507+
$container->set('request_stack', $requestStack);
502508

503509
$controller = $this->createController();
504510
$controller->setContainer($container);

src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/SessionPassTest.php

+53-2
Original file line numberDiff line numberDiff line change
@@ -19,26 +19,77 @@
1919
class SessionPassTest extends TestCase
2020
{
2121
public function testProcess()
22+
{
23+
$container = new ContainerBuilder();
24+
$container
25+
->register('session.storage'); // marker service
26+
$container
27+
->register('.session.do-not-use');
28+
29+
(new SessionPass())->process($container);
30+
31+
$this->assertTrue($container->hasAlias('session'));
32+
$this->assertSame($container->findDefinition('session'), $container->getDefinition('.session.do-not-use'));
33+
$this->assertTrue($container->getAlias('session')->isDeprecated());
34+
}
35+
36+
public function testProcessUserDefinedSession()
2237
{
2338
$arguments = [
2439
new Reference('session.flash_bag'),
2540
new Reference('session.attribute_bag'),
2641
];
2742
$container = new ContainerBuilder();
43+
$container
44+
->register('session.storage'); // marker service
2845
$container
2946
->register('session')
3047
->setArguments($arguments);
3148
$container
3249
->register('session.flash_bag')
33-
->setFactory([new Reference('session'), 'getFlashBag']);
50+
->setFactory([new Reference('.session.do-not-use'), 'getFlashBag']);
3451
$container
3552
->register('session.attribute_bag')
36-
->setFactory([new Reference('session'), 'getAttributeBag']);
53+
->setFactory([new Reference('.session.do-not-use'), 'getAttributeBag']);
3754

3855
(new SessionPass())->process($container);
3956

4057
$this->assertSame($arguments, $container->getDefinition('session')->getArguments());
4158
$this->assertNull($container->getDefinition('session.flash_bag')->getFactory());
4259
$this->assertNull($container->getDefinition('session.attribute_bag')->getFactory());
60+
$this->assertTrue($container->hasAlias('.session.do-not-use'));
61+
$this->assertSame($container->getDefinition('session'), $container->findDefinition('.session.do-not-use'));
62+
$this->assertTrue($container->getDefinition('session')->isDeprecated());
63+
}
64+
65+
public function testProcessUserDefinedAlias()
66+
{
67+
$arguments = [
68+
new Reference('session.flash_bag'),
69+
new Reference('session.attribute_bag'),
70+
];
71+
$container = new ContainerBuilder();
72+
$container
73+
->register('session.storage'); // marker service
74+
$container
75+
->register('trueSession')
76+
->setArguments($arguments);
77+
$container
78+
->setAlias('session', 'trueSession');
79+
$container
80+
->register('session.flash_bag')
81+
->setFactory([new Reference('.session.do-not-use'), 'getFlashBag']);
82+
$container
83+
->register('session.attribute_bag')
84+
->setFactory([new Reference('.session.do-not-use'), 'getAttributeBag']);
85+
86+
(new SessionPass())->process($container);
87+
88+
$this->assertSame($arguments, $container->findDefinition('session')->getArguments());
89+
$this->assertNull($container->getDefinition('session.flash_bag')->getFactory());
90+
$this->assertNull($container->getDefinition('session.attribute_bag')->getFactory());
91+
$this->assertTrue($container->hasAlias('.session.do-not-use'));
92+
$this->assertSame($container->findDefinition('session'), $container->findDefinition('.session.do-not-use'));
93+
$this->assertTrue($container->getAlias('session')->isDeprecated());
4394
}
4495
}

src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php

+3-2
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
use Symfony\Component\HttpClient\MockHttpClient;
4747
use Symfony\Component\HttpClient\RetryableHttpClient;
4848
use Symfony\Component\HttpClient\ScopingHttpClient;
49+
use Symfony\Component\HttpFoundation\Session\SessionInterface;
4950
use Symfony\Component\HttpKernel\DependencyInjection\LoggerPass;
5051
use Symfony\Component\Messenger\Transport\TransportFactory;
5152
use Symfony\Component\PropertyAccess\PropertyAccessor;
@@ -541,7 +542,7 @@ public function testSession()
541542
{
542543
$container = $this->createContainerFromFile('full');
543544

544-
$this->assertTrue($container->hasDefinition('session'), '->registerSessionConfiguration() loads session.xml');
545+
$this->assertTrue($container->hasAlias(SessionInterface::class), '->registerSessionConfiguration() loads session.xml');
545546
$this->assertEquals('fr', $container->getParameter('kernel.default_locale'));
546547
$this->assertEquals('session.storage.native', (string) $container->getAlias('session.storage'));
547548
$this->assertEquals('session.handler.native_file', (string) $container->getAlias('session.handler'));
@@ -567,7 +568,7 @@ public function testNullSessionHandler()
567568
{
568569
$container = $this->createContainerFromFile('session');
569570

570-
$this->assertTrue($container->hasDefinition('session'), '->registerSessionConfiguration() loads session.xml');
571+
$this->assertTrue($container->hasAlias(SessionInterface::class), '->registerSessionConfiguration() loads session.xml');
571572
$this->assertNull($container->getDefinition('session.storage.native')->getArgument(1));
572573
$this->assertNull($container->getDefinition('session.storage.php_bridge')->getArgument(0));
573574
$this->assertSame('session.handler.native_file', (string) $container->getAlias('session.handler'));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
namespace Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller;
4+
5+
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
6+
use Symfony\Component\HttpFoundation\Response;
7+
8+
class DeprecatedSessionController extends AbstractController
9+
{
10+
public function triggerAction()
11+
{
12+
$this->get('session');
13+
14+
return new Response('done');
15+
}
16+
}

src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/Resources/config/routing.yml

+4
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ injected_flashbag_session_setflash:
2222
path: injected_flashbag/session_setflash/{message}
2323
defaults: { _controller: Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\InjectedFlashbagSessionController::setFlashAction}
2424

25+
deprecated_session_setflash:
26+
path: /deprecated_session/trigger
27+
defaults: { _controller: Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\DeprecatedSessionController::triggerAction}
28+
2529
session_showflash:
2630
path: /session_showflash
2731
defaults: { _controller: Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\SessionController::showFlashAction }

0 commit comments

Comments
 (0)
0