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

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 Symfony\Component\HttpFoundation\Session\Session;
  12. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  13. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  14. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  15. use Symfony\Component\HttpKernel\KernelEvents;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. /**
  18.  * Sets the session in the request.
  19.  *
  20.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  21.  */
  22. abstract class AbstractSessionListener implements EventSubscriberInterface
  23. {
  24.     public function onKernelRequest(GetResponseEvent $event)
  25.     {
  26.         if (!$event->isMasterRequest()) {
  27.             return;
  28.         }
  29.         $request $event->getRequest();
  30.         $session $this->getSession();
  31.         if (null === $session || $request->hasSession()) {
  32.             return;
  33.         }
  34.         $request->setSession($session);
  35.     }
  36.     public function onKernelResponse(FilterResponseEvent $event)
  37.     {
  38.         if (!$event->isMasterRequest()) {
  39.             return;
  40.         }
  41.         if (!$session $event->getRequest()->getSession()) {
  42.             return;
  43.         }
  44.         if ($session->isStarted() || ($session instanceof Session && $session->hasBeenStarted())) {
  45.             $event->getResponse()
  46.                 ->setPrivate()
  47.                 ->setMaxAge(0)
  48.                 ->headers->addCacheControlDirective('must-revalidate');
  49.         }
  50.     }
  51.     public static function getSubscribedEvents()
  52.     {
  53.         return array(
  54.             KernelEvents::REQUEST => array('onKernelRequest'128),
  55.             // low priority to come after regular response listeners, same as SaveSessionListener
  56.             KernelEvents::RESPONSE => array('onKernelResponse', -1000),
  57.         );
  58.     }
  59.     /**
  60.      * Gets the session object.
  61.      *
  62.      * @return SessionInterface|null A SessionInterface instance or null if no session is available
  63.      */
  64.     abstract protected function getSession();
  65. }