4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel\EventListener;
14 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
15 use Symfony\Component\HttpFoundation\Session\Session;
16 use Symfony\Component\HttpFoundation\Session\SessionInterface;
17 use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
18 use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
19 use Symfony\Component\HttpKernel\Event\GetResponseEvent;
20 use Symfony\Component\HttpKernel\KernelEvents;
23 * Sets the session in the request.
25 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
27 abstract class AbstractSessionListener implements EventSubscriberInterface
29 private $sessionUsageStack = array();
31 public function onKernelRequest(GetResponseEvent $event)
33 if (!$event->isMasterRequest()) {
37 $request = $event->getRequest();
38 $session = $this->getSession();
39 $this->sessionUsageStack[] = $session instanceof Session ? $session->getUsageIndex() : null;
40 if (null === $session || $request->hasSession()) {
44 $request->setSession($session);
47 public function onKernelResponse(FilterResponseEvent $event)
49 if (!$event->isMasterRequest()) {
53 if (!$session = $event->getRequest()->getSession()) {
57 if ($session instanceof Session ? $session->getUsageIndex() !== end($this->sessionUsageStack) : $session->isStarted()) {
61 ->headers->addCacheControlDirective('must-revalidate');
68 public function onFinishRequest(FinishRequestEvent $event)
70 if ($event->isMasterRequest()) {
71 array_pop($this->sessionUsageStack);
75 public static function getSubscribedEvents()
78 KernelEvents::REQUEST => array('onKernelRequest', 128),
79 // low priority to come after regular response listeners, same as SaveSessionListener
80 KernelEvents::RESPONSE => array('onKernelResponse', -1000),
81 KernelEvents::FINISH_REQUEST => array('onFinishRequest'),
86 * Gets the session object.
88 * @return SessionInterface|null A SessionInterface instance or null if no session is available
90 abstract protected function getSession();