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

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.  * @internal since Symfony 4.3
  33.  */
  34. abstract class AbstractSessionListener implements EventSubscriberInterface
  35. {
  36.     public const NO_AUTO_CACHE_CONTROL_HEADER 'Symfony-Session-NoAutoCacheControl';
  37.     protected $container;
  38.     private $sessionUsageStack = [];
  39.     public function __construct(ContainerInterface $container null)
  40.     {
  41.         $this->container $container;
  42.     }
  43.     public function onKernelRequest(GetResponseEvent $event)
  44.     {
  45.         if (!$event->isMasterRequest()) {
  46.             return;
  47.         }
  48.         $session null;
  49.         $request $event->getRequest();
  50.         if (!$request->hasSession()) {
  51.             $sess null;
  52.             $request->setSessionFactory(function () use (&$sess) { return $sess ?? $sess $this->getSession(); });
  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.     {
  59.         if (!$event->isMasterRequest()) {
  60.             return;
  61.         }
  62.         $response $event->getResponse();
  63.         $autoCacheControl = !$response->headers->has(self::NO_AUTO_CACHE_CONTROL_HEADER);
  64.         // Always remove the internal header if present
  65.         $response->headers->remove(self::NO_AUTO_CACHE_CONTROL_HEADER);
  66.         if (!$session $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : $event->getRequest()->getSession()) {
  67.             return;
  68.         }
  69.         if ($session instanceof Session $session->getUsageIndex() !== end($this->sessionUsageStack) : $session->isStarted()) {
  70.             if ($autoCacheControl) {
  71.                 $response
  72.                     ->setExpires(new \DateTime())
  73.                     ->setPrivate()
  74.                     ->setMaxAge(0)
  75.                     ->headers->addCacheControlDirective('must-revalidate');
  76.             }
  77.         }
  78.         if ($session->isStarted()) {
  79.             /*
  80.              * Saves the session, in case it is still open, before sending the response/headers.
  81.              *
  82.              * This ensures several things in case the developer did not save the session explicitly:
  83.              *
  84.              *  * If a session save handler without locking is used, it ensures the data is available
  85.              *    on the next request, e.g. after a redirect. PHPs auto-save at script end via
  86.              *    session_register_shutdown is executed after fastcgi_finish_request. So in this case
  87.              *    the data could be missing the next request because it might not be saved the moment
  88.              *    the new request is processed.
  89.              *  * A locking save handler (e.g. the native 'files') circumvents concurrency problems like
  90.              *    the one above. But by saving the session before long-running things in the terminate event,
  91.              *    we ensure the session is not blocked longer than needed.
  92.              *  * When regenerating the session ID no locking is involved in PHPs session design. See
  93.              *    https://bugs.php.net/61470 for a discussion. So in this case, the session must
  94.              *    be saved anyway before sending the headers with the new session ID. Otherwise session
  95.              *    data could get lost again for concurrent requests with the new ID. One result could be
  96.              *    that you get logged out after just logging in.
  97.              *
  98.              * This listener should be executed as one of the last listeners, so that previous listeners
  99.              * can still operate on the open session. This prevents the overhead of restarting it.
  100.              * Listeners after closing the session can still work with the session as usual because
  101.              * Symfonys session implementation starts the session on demand. So writing to it after
  102.              * it is saved will just restart it.
  103.              */
  104.             $session->save();
  105.         }
  106.     }
  107.     /**
  108.      * @internal
  109.      */
  110.     public function onFinishRequest(FinishRequestEvent $event)
  111.     {
  112.         if ($event->isMasterRequest()) {
  113.             array_pop($this->sessionUsageStack);
  114.         }
  115.     }
  116.     public static function getSubscribedEvents()
  117.     {
  118.         return [
  119.             KernelEvents::REQUEST => ['onKernelRequest'128],
  120.             // low priority to come after regular response listeners, but higher than StreamedResponseListener
  121.             KernelEvents::RESPONSE => ['onKernelResponse', -1000],
  122.             KernelEvents::FINISH_REQUEST => ['onFinishRequest'],
  123.         ];
  124.     }
  125.     /**
  126.      * Gets the session object.
  127.      *
  128.      * @return SessionInterface|null A SessionInterface instance or null if no session is available
  129.      */
  130.     abstract protected function getSession();
  131. }