getSession example



  /** * Asserts the number of BigPipe placeholders that are replaced on the page. * * @param int $expected_count * The expected number of BigPipe placeholders. */
  protected function assertBigPipePlaceholderReplacementCount($expected_count): void {
    $web_assert = $this->assertSession();
    $web_assert->waitForElement('css', 'script[data-big-pipe-event="stop"]');
    $page = $this->getSession()->getPage();
    // Settings are removed as soon as they are processed.     $this->assertCount(0, $this->getDrupalSettings()['bigPipePlaceholderIds']);
    $this->assertCount($expected_count$page->findAll('css', 'script[data-big-pipe-replacement-for-placeholder-with-id]'));
  }

}
->setOverridable()
      ->save();
    $this->createNode(['type' => 'bundle_with_section_field']);
  }

  /** * Tests that validation messages are shown on the block form. */
  public function testValidationMessage() {
    // @todo Work out why this fixes random fails in this test.     // https://www.drupal.org/project/drupal/issues/3055982     $this->getSession()->resizeWindow(800, 1000);
    $assert_session = $this->assertSession();
    $page = $this->getSession()->getPage();

    $this->drupalLogin($this->drupalCreateUser([
      'access contextual links',
      'configure any layout',
    ]));
    $this->drupalGet('node/1/layout');
    $page->findLink('Add block')->click();
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '#drupal-off-canvas .block-categories'));
    $page->findLink('Powered by Drupal')->click();
    
'#type' => 'password_confirm',
        '#size' => 25,
        '#description' => $this->t('To change the current user password, enter the new password in both fields.'),
      ];

      // To skip the current password field, the user must have logged in via a       // one-time link and have the token in the URL. Store this in $form_state       // so it persists even on subsequent Ajax requests.       $request = $this->getRequest();
      if (!$form_state->get('user_pass_reset') && ($token = $request->query->get('pass-reset-token'))) {
        $session_key = 'pass_reset_' . $account->id();
        $session_value = $request->getSession()->get($session_key);
        $user_pass_reset = isset($session_value) && hash_equals($session_value$token);
        $form_state->set('user_pass_reset', $user_pass_reset);
      }

      // The user must enter their current password to change to a new one.       if ($user->id() == $account->id()) {
        $form['account']['current_pass'] = [
          '#type' => 'password',
          '#title' => $this->t('Current password'),
          '#size' => 25,
          '#access' => !$form_state->get('user_pass_reset'),
          
public function supports(Request $request): bool
    {
        return $request->isMethod('POST') && $this->getLoginUrl($request) === $request->getBaseUrl().$request->getPathInfo();
    }

    /** * Override to change what happens after a bad username/password is submitted. */
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
    {
        if ($request->hasSession()) {
            $request->getSession()->set(SecurityRequestAttributes::AUTHENTICATION_ERROR, $exception);
        }

        $url = $this->getLoginUrl($request);

        return new RedirectResponse($url);
    }

    /** * Override to control what happens when the user hits a secure page * but isn't logged in yet. */
    
 else {
                $attributes[$key] = $value;
            }
        }

        $content = $request->getContent();

        $sessionMetadata = [];
        $sessionAttributes = [];
        $flashes = [];
        if ($request->hasSession()) {
            $session = $request->getSession();
            if ($session->isStarted()) {
                $sessionMetadata['Created'] = date(\DATE_RFC822, $session->getMetadataBag()->getCreated());
                $sessionMetadata['Last used'] = date(\DATE_RFC822, $session->getMetadataBag()->getLastUsed());
                $sessionMetadata['Lifetime'] = $session->getMetadataBag()->getLifetime();
                $sessionAttributes = $session->all();
                $flashes = $session->getFlashBag()->peekAll();
            }
        }

        $statusCode = $response->getStatusCode();

        
'administer views',
    ]);
    $this->drupalLogin($admin_user);
  }

  /** * Tests filtering options in the 'Add fields' dialog. */
  public function testFilterOptionsAddFields() {
    $this->drupalGet('admin/structure/views/view/content');

    $session = $this->getSession();
    $web_assert = $this->assertSession();
    $page = $session->getPage();

    // Open the dialog.     $page->clickLink('views-add-field');

    // Wait for the popup to open and the search field to be available.     $options_search = $web_assert->waitForField('override[controls][options_search]');

    // Test that the both special fields are visible.     $this->assertTrue($page->findField('name[views.views_test_field_1]')->isVisible());
    

  public function set($key$value) {
    if ($this->currentUser->isAnonymous()) {
      // Ensure that an anonymous user has a session created for them, as       // otherwise subsequent page loads will not be able to retrieve their       // tempstore data. Note this has to be done before the key is created as       // the owner is used in key creation.       $this->startSession();
      $session = $this->requestStack->getCurrentRequest()->getSession();
      if (!$session->has('core.tempstore.private.owner')) {
        $session->set('core.tempstore.private.owner', Crypt::randomBytesBase64());
      }
    }

    $key = $this->createkey($key);
    if (!$this->lockBackend->acquire($key)) {
      $this->lockBackend->wait($key);
      if (!$this->lockBackend->acquire($key)) {
        throw new TempStoreException("Couldn't acquire lock to update item '$key' in '{$this->storage->getCollectionName()}' temporary storage.");
      }
    }
$this->logger?->debug('Authentication failure, forward triggered.', ['failure_path' => $options['failure_path']]);

            $subRequest = $this->httpUtils->createRequest($request$options['failure_path']);
            $subRequest->attributes->set(SecurityRequestAttributes::AUTHENTICATION_ERROR, $exception);

            return $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
        }

        $this->logger?->debug('Authentication failure, redirect triggered.', ['failure_path' => $options['failure_path']]);

        if (!$request->attributes->getBoolean('_stateless')) {
            $request->getSession()->set(SecurityRequestAttributes::AUTHENTICATION_ERROR, $exception);
        }

        return $this->httpUtils->createRedirectResponse($request$options['failure_path']);
    }
}
->set('standalone_url', TRUE)
      ->save(TRUE);

    $this->container->get('router.builder')->rebuild();
  }

  /** * Tests basic media display. */
  public function testMediaDisplay() {
    $assert_session = $this->assertSession();
    $page = $this->getSession()->getPage();

    $media_type = $this->createMediaType('test');

    // Create a media item.     $media = Media::create([
      'bundle' => $media_type->id(),
      'name' => 'Fantastic!',
    ]);
    $media->save();

    $this->drupalGet('media/' . $media->id());
    
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());
        }

        $salesChannelId = $master->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID);
        if ($salesChannelId === null) {
            /** @var SalesChannelContext|null $salesChannelContext */
            $salesChannelContext = $master->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
            
#[Route(path: '/installer/finish', name: 'installer.finish', methods: ['GET'])]     public function finish(Request $request): Response
    {
        $this->systemLocker->lock();

        $additionalInformation = [
            'language' => $request->attributes->get('_locale'),
            'method' => 'installer',
        ];
        $this->notifier->doTrackEvent(Notifier::EVENT_INSTALL_FINISHED, $additionalInformation);

        $session = $request->getSession();
        /** @var array<string, string> $adminInfo */
        $adminInfo = $session->get('ADMIN_USER', []);

        $data = [
            'grant_type' => 'password',
            'client_id' => 'administration',
            'scopes' => 'write',
            'username' => $adminInfo['username'] ?? '',
            'password' => $adminInfo['password'] ?? '',
        ];

        
/** * Tests that the 'toolbar/subtrees/{hash}' is reachable and correct. */
  public function testSubtreesJsonRequest() {
    $admin_user = $this->adminUser;
    $this->drupalLogin($admin_user);
    // Request a new page to refresh the drupalSettings object.     $subtrees_hash = $this->getSubtreesHash();

    $this->drupalGet('toolbar/subtrees/' . $subtrees_hash['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]['X-Requested-With: XMLHttpRequest']);
    $ajax_result = json_decode($this->getSession()->getPage()->getContent(), TRUE);
    $this->assertEquals('setToolbarSubtrees', $ajax_result[0]['command'], 'Subtrees response uses the correct command.');
    $this->assertEquals(['system-admin_content', 'system-admin_structure', 'system-themes_page', 'system-modules_list', 'system-admin_config', 'entity-user-collection', 'front']array_keys($ajax_result[0]['subtrees']), 'Correct subtrees returned.');
  }

  /** * Tests that subtrees hashes vary by the language of the page. */
  public function testLanguageSwitching() {
    // Create a new language with the langcode 'xx'.     $langcode = 'xx';
    $language = ConfigurableLanguage::createFromLangcode($langcode);
    
/** * Builds a query for database log administration filters based on session. * * @param \Symfony\Component\HttpFoundation\Request $request * The request. * * @return array|null * An associative array with keys 'where' and 'args' or NULL if there were * no filters set. */
  protected function buildFilterQuery(Request $request) {
    $session_filters = $request->getSession()->get('dblog_overview_filter', []);
    if (empty($session_filters)) {
      return;
    }

    $this->moduleHandler()->loadInclude('dblog', 'admin.inc');

    $filters = dblog_filters();

    // Build query.     $where = $args = [];
    foreach ($session_filters as $key => $filter) {
      

        $request = $event->getRequest();

        /** @var list<string> $scopes */
        $scopes = $request->attributes->get(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, []);

        // Only process storefront routes         if (!\in_array(StorefrontRouteScope::ID, $scopes, true)) {
            return;
        }

        $session = $request->getSession();
        $affiliateCode = $request->query->get(self::AFFILIATE_CODE_KEY);
        $campaignCode = $request->query->get(self::CAMPAIGN_CODE_KEY);
        if ($affiliateCode) {
            $session->set(self::AFFILIATE_CODE_KEY, $affiliateCode);
        }

        if ($campaignCode) {
            $session->set(self::CAMPAIGN_CODE_KEY, $campaignCode);
        }
    }
}
return $this->requests[$pos] ?? null;
    }

    /** * Gets the current session. * * @throws SessionNotFoundException */
    public function getSession(): SessionInterface
    {
        if ((null !== $request = end($this->requests) ?: null) && $request->hasSession()) {
            return $request->getSession();
        }

        throw new SessionNotFoundException();
    }
}
Home | Imprint | This part of the site doesn't use cookies.