SessionTestSubscriber.php

Same filename in other branches
  1. 9 core/modules/system/tests/modules/session_test/src/EventSubscriber/SessionTestSubscriber.php
  2. 8.9.x core/modules/system/tests/modules/session_test/src/EventSubscriber/SessionTestSubscriber.php
  3. 11.x core/modules/system/tests/modules/session_test/src/EventSubscriber/SessionTestSubscriber.php

Namespace

Drupal\session_test\EventSubscriber

File

core/modules/system/tests/modules/session_test/src/EventSubscriber/SessionTestSubscriber.php

View source
<?php

namespace Drupal\session_test\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;

/**
 * Defines a test session subscriber that checks whether the session is empty.
 */
class SessionTestSubscriber implements EventSubscriberInterface {
    
    /**
     * Stores whether the session is empty at the beginning of the request.
     *
     * @var bool
     */
    protected $emptySession;
    
    /**
     * Set header for session testing.
     *
     * @param \Symfony\Component\HttpKernel\Event\RequestEvent $event
     *   The Event to process.
     */
    public function onKernelRequestSessionTest(RequestEvent $event) {
        $session = $event->getRequest()
            ->getSession();
        $this->emptySession = !($session && $session->start());
    }
    
    /**
     * Performs tasks for session_test module on kernel.response.
     *
     * @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event
     *   The Event to process.
     */
    public function onKernelResponseSessionTest(ResponseEvent $event) {
        // Set header for session testing.
        $response = $event->getResponse();
        $response->headers
            ->set('X-Session-Empty', $this->emptySession ? '1' : '0');
    }
    
    /**
     * Registers the methods in this class that should be listeners.
     *
     * @return array
     *   An array of event listener definitions.
     */
    public static function getSubscribedEvents() : array {
        $events[KernelEvents::RESPONSE][] = [
            'onKernelResponseSessionTest',
        ];
        $events[KernelEvents::REQUEST][] = [
            'onKernelRequestSessionTest',
        ];
        return $events;
    }

}

Classes

Title Deprecated Summary
SessionTestSubscriber Defines a test session subscriber that checks whether the session is empty.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.