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\Cookie;
16 use Symfony\Component\HttpFoundation\Session\Session;
17 use Symfony\Component\HttpFoundation\Session\SessionInterface;
18 use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
19 use Symfony\Component\HttpKernel\Event\GetResponseEvent;
20 use Symfony\Component\HttpKernel\KernelEvents;
23 * TestSessionListener.
25 * Saves session in test environment.
27 * @author Bulat Shakirzyanov <mallluhuct@gmail.com>
28 * @author Fabien Potencier <fabien@symfony.com>
30 abstract class AbstractTestSessionListener implements EventSubscriberInterface
34 public function onKernelRequest(GetResponseEvent $event)
36 if (!$event->isMasterRequest()) {
40 // bootstrap the session
41 $session = $this->getSession();
46 $cookies = $event->getRequest()->cookies;
48 if ($cookies->has($session->getName())) {
49 $this->sessionId = $cookies->get($session->getName());
50 $session->setId($this->sessionId);
55 * Checks if session was initialized and saves if current request is master
56 * Runs on 'kernel.response' in test environment.
58 public function onKernelResponse(FilterResponseEvent $event)
60 if (!$event->isMasterRequest()) {
64 if (!$session = $event->getRequest()->getSession()) {
68 if ($wasStarted = $session->isStarted()) {
72 if ($session instanceof Session ? !$session->isEmpty() || (null !== $this->sessionId && $session->getId() !== $this->sessionId) : $wasStarted) {
73 $params = session_get_cookie_params();
75 foreach ($event->getResponse()->headers->getCookies() as $cookie) {
76 if ($session->getName() === $cookie->getName() && $params['path'] === $cookie->getPath() && $params['domain'] == $cookie->getDomain()) {
81 $event->getResponse()->headers->setCookie(new Cookie($session->getName(), $session->getId(), 0 === $params['lifetime'] ? 0 : time() + $params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly']));
82 $this->sessionId = $session->getId();
86 public static function getSubscribedEvents()
89 KernelEvents::REQUEST => array('onKernelRequest', 192),
90 KernelEvents::RESPONSE => array('onKernelResponse', -128),
95 * Gets the session object.
97 * @return SessionInterface|null A SessionInterface instance or null if no session is available
99 abstract protected function getSession();