|
| 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\Component\HttpKernel\EventListener; |
| 13 | + |
| 14 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 15 | +use Symfony\Component\HttpKernel\Event\FinishRequestEvent; |
| 16 | +use Symfony\Component\HttpKernel\KernelEvents; |
| 17 | + |
| 18 | +/** |
| 19 | + * Saves the session, in case it is still open, before sending the response. |
| 20 | + * |
| 21 | + * This ensures several things in case the developer did not save the session explicitly: |
| 22 | + * |
| 23 | + * * If a session save handler without locking is used, it ensures the data is available |
| 24 | + * on the next request, e.g. after a redirect. PHPs auto-save at script end via |
| 25 | + * session_register_shutdown is executed after fastcgi_finish_request. So in this case |
| 26 | + * the data could be missing the next request because it might not be saved the moment |
| 27 | + * the new request is processed. |
| 28 | + * * A locking save handler (e.g. the native 'files') circumvents concurrency problems like |
| 29 | + * the one above. By saving the session before long-running things in the terminate event, |
| 30 | + * we ensure the session is not blocked longer than needed. |
| 31 | + * * In case of a regenerated session ID locking cannot help. So it this case, the session |
| 32 | + * must be saved anyway before sending the response to not be logged out after just |
| 33 | + * logging in. |
| 34 | + * |
| 35 | + * @author Tobias Schultze <http://tobion.de> |
| 36 | + */ |
| 37 | +class SaveSessionListener implements EventSubscriberInterface |
| 38 | +{ |
| 39 | + public function onKernelFinishRequest(FinishRequestEvent $event) |
| 40 | + { |
| 41 | + if (!$event->isMasterRequest()) { |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + $session = $event->getRequest()->getSession(); |
| 46 | + if ($session && $session->isStarted()) { |
| 47 | + $session->save(); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public static function getSubscribedEvents() |
| 52 | + { |
| 53 | + return array( |
| 54 | + KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', -1000)), |
| 55 | + ); |
| 56 | + } |
| 57 | +} |
0 commit comments