hasSession example

$this->debug = $debug;
        $this->sessionOptions = $sessionOptions;
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $request = $event->getRequest();
        if (!$request->hasSession()) {
            $request->setSessionFactory(function D) use ($request) {
                // Prevent calling `$this->getSession()` twice in case the Request (and the below factory) is cloned                 static $sess;

                if (!$sess) {
                    $sess = $this->getSession();
                    $request->setSession($sess);

                    /* * For supporting sessions in php runtime with runners like roadrunner or swoole, the session * cookie needs to be read from the cookie bag and set on the session storage. * * Do not set it when a native php session is active. */


        $groups = [
            'info' => $errors->getNotices(),
            'warning' => $errors->getWarnings(),
            'danger' => $errors->getErrors(),
        ];

        $request = $this->container->get('request_stack')->getMainRequest();
        $exists = [];

        if ($request && $request->hasSession() && $request->getSession() instanceof FlashBagAwareSessionInterface) {
            $exists = $request->getSession()->getFlashBag()->peekAll();
        }

        $flat = [];
        foreach ($exists as $messages) {
            $flat = array_merge($flat$messages);
        }

        /** @var array<string, Error[]> $groups */
        foreach ($groups as $type => $errors) {
            foreach ($errors as $error) {
                
$session->start();
    $request->setSession($session);
  }

  /** * Ensures that the session is saved. * * @param \Symfony\Component\HttpFoundation\Request $request * The incoming request. */
  protected function shutdownSession(Request $request) {
    if ($request->hasSession()) {
      $request->getSession()->save();
    }
  }

  /** * Set up the request with fake routing data for update.php. * * This fake routing data is needed in order to make batch API work properly. * * @param \Symfony\Component\HttpFoundation\Request $request * The incoming request. */
return $session;
    }

    /** * Whether the request contains a Session which was started in one of the * previous requests. */
    public function hasPreviousSession(): bool
    {
        // the check for $this->session avoids malicious users trying to fake a session cookie with proper name         return $this->hasSession() && $this->cookies->has($this->getSession()->getName());
    }

    /** * Whether the request contains a Session object. * * This method does not give any information about the state of the session object, * like whether the session is started or not. It is just a way to check if this Request * is associated with a Session instance. * * @param bool $skipIfUninitialized When true, ignores factories injected by `setSessionFactory` */
    
/** * @internal */
#[Package('core')] class FinishController extends AbstractController
{
    #[Route('/finish', name: 'finish', defaults: ['step' => 3])]     public function default(Request $request, #[Autowire('%kernel.cache_dir%')] string $cacheDir): Response     {
        // @codeCoverageIgnoreStart         if ($request->getMethod() === Request::METHOD_POST) {
            if ($request->hasSession()) {
                $request->getSession()->invalidate();
            }

            $self = $_SERVER['SCRIPT_FILENAME'];
            \assert(\is_string($self));

            $redirectUrl = $request->getBasePath() . '/admin';

            // Cleanup our generated cache dir in system temporary directory             $fs = new Filesystem();
            $fs->remove($cacheDir);

            
return FALSE;
  }

  /** * Stores the owner in the session if the user is anonymous. * * This method should be called when a value is set. */
  protected function ensureAnonymousSession() {
    // If this is being run from the CLI then the request will not have a     // session.     if ($this->currentUser->isAnonymous() && $this->requestStack->getCurrentRequest()->hasSession()) {
      $this->requestStack->getCurrentRequest()->getSession()->set('core.tempstore.shared.owner', $this->owner);
    }
  }

}
public function startSession(): void
    {
        $master = $this->requestStack->getMainRequest();

        if (!$master) {
            return;
        }
        if (!$master->attributes->get(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
            return;
        }

        if (!$master->hasSession()) {
            return;
        }

        $session = $master->getSession();

        if (!$session->isStarted()) {
            $session->setName('session-');
            $session->start();
            $session->set('sessionId', $session->getId());
        }

        
$given = get_debug_type($response);

            throw new \LogicException(sprintf('The "%s::start()" method must return a Response object ("%s" returned).', get_debug_type($this->authenticationEntryPoint)$given));
        }

        return $response;
    }

    protected function setTargetPath(Request $request): void
    {
        // session isn't required when using HTTP basic authentication mechanism for example         if ($request->hasSession() && $request->isMethodSafe() && !$request->isXmlHttpRequest()) {
            $this->saveTargetPath($request->getSession()$this->firewallName, $request->getUri());
        }
    }

    private function throwUnauthorizedException(AuthenticationException $authException): never
    {
        $this->logger?->notice(sprintf('No Authentication entry point configured, returning a %s HTTP response. Configure "entry_point" on the firewall "%s" if you want to modify the response.', Response::HTTP_UNAUTHORIZED, $this->firewallName));

        throw new HttpException(Response::HTTP_UNAUTHORIZED, $authException->getMessage()$authException[]$authException->getCode());
    }
}
return $session;
    }

    /** * Whether the request contains a Session which was started in one of the * previous requests. */
    public function hasPreviousSession(): bool
    {
        // the check for $this->session avoids malicious users trying to fake a session cookie with proper name         return $this->hasSession() && $this->cookies->has($this->getSession()->getName());
    }

    /** * Whether the request contains a Session object. * * This method does not give any information about the state of the session object, * like whether the session is started or not. It is just a way to check if this Request * is associated with a Session instance. * * @param bool $skipIfUninitialized When true, ignores factories injected by `setSessionFactory` */
    

  protected function startSession() {
    $has_session = $this->requestStack
      ->getCurrentRequest()
      ->hasSession();
    if (!$has_session) {
      /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface $session */
      $session = \Drupal::service('session');
      $this->requestStack->getCurrentRequest()->setSession($session);
      $session->start();
    }
  }

}

        session_start();
        $sessionId = session_id();

        $request = new Request();
        $listener = $this->createListener($requestnew PhpBridgeSessionStorageFactory());

        $event = new RequestEvent($this->createMock(HttpKernelInterface::class)$request, HttpKernelInterface::MAIN_REQUEST);

        $listener->onKernelRequest($event);

        $this->assertTrue($request->hasSession());
        $this->assertSame($sessionId$request->getSession()->getId());
    }

    /** * @runInSeparateProcess */
    public function testSessionCookieWrittenNoCookieGiven()
    {
        $request = new Request();
        $listener = $this->createListener($requestnew NativeSessionStorageFactory());

        

        $this->requestStack = $requestStack;
    }

    public function getLastAuthenticationError(bool $clearSession = true): ?AuthenticationException
    {
        $request = $this->getRequest();
        $authenticationException = null;

        if ($request->attributes->has(SecurityRequestAttributes::AUTHENTICATION_ERROR)) {
            $authenticationException = $request->attributes->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);
        } elseif ($request->hasSession() && ($session = $request->getSession())->has(SecurityRequestAttributes::AUTHENTICATION_ERROR)) {
            $authenticationException = $session->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);

            if ($clearSession) {
                $session->remove(SecurityRequestAttributes::AUTHENTICATION_ERROR);
            }
        }

        return $authenticationException;
    }

    public function getLastUsername(): string
    {

  public function handle(Request $request$type = self::MAIN_REQUEST, $catch = TRUE): Response {
    if ($type === self::MAIN_REQUEST && PHP_SAPI !== 'cli') {
      $session = $this->container->get($this->sessionServiceName);
      $session->start();
      $request->setSession($session);
    }

    $result = $this->httpKernel->handle($request$type$catch);

    if ($type === self::MAIN_REQUEST && $request->hasSession()) {
      $request->getSession()->save();
    }

    return $result;
  }

}
/** * Writes the security token into the session. */
    public function onKernelResponse(ResponseEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $request = $event->getRequest();

        if (!$request->hasSession() || $request->attributes->get('_security_firewall_run') !== $this->sessionKey) {
            return;
        }

        $this->dispatcher?->removeListener(KernelEvents::RESPONSE, $this->onKernelResponse(...));
        $this->registered = false;
        $session = $request->getSession();
        $sessionId = $session->getId();
        $usageIndexValue = $session instanceof Session ? $usageIndexReference = &$session->getUsageIndex() : null;
        $token = $this->tokenStorage->getToken();

        if (!$this->trustResolver->isAuthenticated($token)) {
            
/** * Renders the Web Debug Toolbar. * * @throws NotFoundHttpException */
    public function toolbarAction(Request $request, string $token = null): Response
    {
        if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        if (!$request->attributes->getBoolean('_stateless') && $request->hasSession()
            && ($session = $request->getSession())->isStarted() && $session->getFlashBag() instanceof AutoExpireFlashBag
        ) {
            // keep current flashes for one more request if using AutoExpireFlashBag             $session->getFlashBag()->setAll($session->getFlashBag()->peekAll());
        }

        if ('empty' === $token || null === $token) {
            return new Response('', 200, ['Content-Type' => 'text/html']);
        }

        $this->profiler->disable();

        
Home | Imprint | This part of the site doesn't use cookies.