vendor/symfony/http-kernel/EventListener/AbstractSessionListener.php line 68

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\HttpKernel\EventListener;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpFoundation\Session\Session;
  14. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  15. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  16. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  17. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  18. use Symfony\Component\HttpKernel\KernelEvents;
  19. /**
  20.  * Sets the session onto the request on the "kernel.request" event and saves
  21.  * it on the "kernel.response" event.
  22.  *
  23.  * In addition, if the session has been started it overrides the Cache-Control
  24.  * header in such a way that all caching is disabled in that case.
  25.  * If you have a scenario where caching responses with session information in
  26.  * them makes sense, you can disable this behaviour by setting the header
  27.  * AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER on the response.
  28.  *
  29.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  30.  * @author Tobias Schultze <http://tobion.de>
  31.  */
  32. abstract class AbstractSessionListener implements EventSubscriberInterface {
  33.     const NO_AUTO_CACHE_CONTROL_HEADER 'Symfony-Session-NoAutoCacheControl';
  34.     protected $container;
  35.     private $sessionUsageStack = [];
  36.     public function __construct(ContainerInterface $container null) {
  37.         $this->container $container;
  38.     }
  39.     public function onKernelRequest(GetResponseEvent $event) {
  40.         if (!$event->isMasterRequest()) {
  41.             return;
  42.         }
  43.         $session null;
  44.         $request $event->getRequest();
  45.         if ($request->hasSession()) {
  46.             // no-op
  47.         } elseif (method_exists($request'setSessionFactory')) {
  48.             $request->setSessionFactory(function () {
  49.                 return $this->getSession();
  50.             });
  51.         } elseif ($session $this->getSession()) {
  52.             $request->setSession($session);
  53.         }
  54.         $session $session ?? ($this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : null);
  55.         $this->sessionUsageStack[] = $session instanceof Session $session->getUsageIndex() : 0;
  56.     }
  57.     public function onKernelResponse(FilterResponseEvent $event) {
  58.         if (!$event->isMasterRequest()) {
  59.             return;
  60.         }
  61.         $response $event->getResponse();
  62.         $autoCacheControl = !$response->headers->has(self::NO_AUTO_CACHE_CONTROL_HEADER);
  63.         // Always remove the internal header if present
  64.         $response->headers->remove(self::NO_AUTO_CACHE_CONTROL_HEADER);
  65.         if (!$session $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : $event->getRequest()->getSession()) {
  66.             return;
  67.         }
  68.         if ($session instanceof Session $session->getUsageIndex() !== end($this->sessionUsageStack) : $session->isStarted()) {
  69.             if ($autoCacheControl) {
  70.                 $response
  71.                         ->setPrivate()
  72.                         ->setMaxAge(0)
  73.                 ->headers->addCacheControlDirective('must-revalidate');
  74.             }
  75.         }
  76.         if ($session->isStarted()) {
  77.             /*
  78.              * Saves the session, in case it is still open, before sending the response/headers.
  79.              *
  80.              * This ensures several things in case the developer did not save the session explicitly:
  81.              *
  82.              *  * If a session save handler without locking is used, it ensures the data is available
  83.              *    on the next request, e.g. after a redirect. PHPs auto-save at script end via
  84.              *    session_register_shutdown is executed after fastcgi_finish_request. So in this case
  85.              *    the data could be missing the next request because it might not be saved the moment
  86.              *    the new request is processed.
  87.              *  * A locking save handler (e.g. the native 'files') circumvents concurrency problems like
  88.              *    the one above. But by saving the session before long-running things in the terminate event,
  89.              *    we ensure the session is not blocked longer than needed.
  90.              *  * When regenerating the session ID no locking is involved in PHPs session design. See
  91.              *    https://bugs.php.net/bug.php?id=61470 for a discussion. So in this case, the session must
  92.              *    be saved anyway before sending the headers with the new session ID. Otherwise session
  93.              *    data could get lost again for concurrent requests with the new ID. One result could be
  94.              *    that you get logged out after just logging in.
  95.              *
  96.              * This listener should be executed as one of the last listeners, so that previous listeners
  97.              * can still operate on the open session. This prevents the overhead of restarting it.
  98.              * Listeners after closing the session can still work with the session as usual because
  99.              * Symfonys session implementation starts the session on demand. So writing to it after
  100.              * it is saved will just restart it.
  101.              */
  102.             $session->save();
  103.         }
  104.     }
  105.     /**
  106.      * @internal
  107.      */
  108.     public function onFinishRequest(FinishRequestEvent $event) {
  109.         if ($event->isMasterRequest()) {
  110.             array_pop($this->sessionUsageStack);
  111.         }
  112.     }
  113.     public static function getSubscribedEvents() {
  114.         return [
  115.             KernelEvents::REQUEST => ['onKernelRequest'128],
  116.             // low priority to come after regular response listeners, but higher than StreamedResponseListener
  117.             KernelEvents::RESPONSE => ['onKernelResponse', -1000],
  118.             KernelEvents::FINISH_REQUEST => ['onFinishRequest'],
  119.         ];
  120.     }
  121.     /**
  122.      * Gets the session object.
  123.      *
  124.      * @return SessionInterface|null A SessionInterface instance or null if no session is available
  125.      */
  126.     abstract protected function getSession();
  127. }