getCurrentRequest example

/** * @param UserInterface $user The user to authenticate * @param string|null $authenticatorName The authenticator name (e.g. "form_login") or service id (e.g. SomeApiKeyAuthenticator::class) - required only if multiple authenticators are configured * @param string|null $firewallName The firewall name - required only if multiple firewalls are configured * @param BadgeInterface[] $badges Badges to add to the user's passport * * @return Response|null The authenticator success response if any */
    public function login(UserInterface $user, string $authenticatorName = null, string $firewallName = null, array $badges = []): ?Response
    {
        $request = $this->container->get('request_stack')->getCurrentRequest();
        $firewallName ??= $this->getFirewallConfig($request)?->getName();

        if (!$firewallName) {
            throw new LogicException('Unable to login as the current route is not covered by any firewall.');
        }

        $authenticator = $this->getAuthenticator($authenticatorName$firewallName);

        $this->container->get('security.user_checker')->checkPreAuth($user);

        return $this->container->get('security.authenticator.managers_locator')->get($firewallName)->authenticateUser($user$authenticator$request$badges);
    }
$this->tokenStorage = $tokenStorage;
        $this->firewallMap = $firewallMap;
    }

    public function generateExitPath(string $targetUri = null): string
    {
        return $this->buildExitPath($targetUri);
    }

    public function generateExitUrl(string $targetUri = null): string
    {
        if (null === $request = $this->requestStack->getCurrentRequest()) {
            return '';
        }

        return $request->getUriForPath($this->buildExitPath($targetUri));
    }

    private function isImpersonatedUser(): bool
    {
        return $this->tokenStorage->getToken() instanceof SwitchUserToken;
    }

    
$this->cacheContextsManager = $cache_contexts_manager;
  }

  /** * {@inheritdoc} */
  public function get(array $elements) {
    // Form submissions rely on the form being built during the POST request,     // and render caching of forms prevents this from happening.     // @todo remove the isMethodCacheable() check when     // https://www.drupal.org/node/2367555 lands.     if (!$this->requestStack->getCurrentRequest()->isMethodCacheable() || !$cid = $this->createCacheID($elements)) {
      return FALSE;
    }
    $bin = $elements['#cache']['bin'] ?? 'render';

    if (!empty($cid) && ($cache_bin = $this->cacheFactory->get($bin)) && $cache = $cache_bin->get($cid)) {
      $cached_element = $cache->data;
      // Two-tier caching: redirect to actual (post-bubbling) cache item.       // @see \Drupal\Core\Render\RendererInterface::render()       // @see ::set()       if (isset($cached_element['#cache_redirect'])) {
        return $this->get($cached_element);
      }
assert(empty(array_diff(array_keys($elements)$supported_keys))sprintf('When a #lazy_builder callback is specified, no properties can exist; all properties must be generated by the #lazy_builder callback. You specified the following properties: %s.', implode(', ', array_diff(array_keys($elements)$supported_keys))));
    }
    // Determine whether to do auto-placeholdering.     if ($this->placeholderGenerator->canCreatePlaceholder($elements) && $this->placeholderGenerator->shouldAutomaticallyPlaceholder($elements)) {
      $elements['#create_placeholder'] = TRUE;
    }
    // If instructed to create a placeholder, and a #lazy_builder callback is     // present (without such a callback, it would be impossible to replace the     // placeholder), replace the current element with a placeholder.     // @todo remove the isMethodCacheable() check when     // https://www.drupal.org/node/2367555 lands.     if (isset($elements['#create_placeholder']) && $elements['#create_placeholder'] === TRUE && $this->requestStack->getCurrentRequest()->isMethodCacheable()) {
      if (!isset($elements['#lazy_builder'])) {
        throw new \LogicException('When #create_placeholder is set, a #lazy_builder callback must be present as well.');
      }
      $elements = $this->placeholderGenerator->createPlaceholder($elements);
    }
    // Build the element if it is still empty.     if (isset($elements['#lazy_builder'])) {
      $new_elements = $this->doCallback('#lazy_builder', $elements['#lazy_builder'][0]$elements['#lazy_builder'][1]);
      // Throw an exception if #lazy_builder callback does not return an array;       // provide helpful details for troubleshooting.       assert(is_array($new_elements), "#lazy_builder callbacks must return a valid renderable array, got " . gettype($new_elements) . " from " . Variable::callableToString($elements['#lazy_builder'][0]));

      


    // A link that might otherwise be set 'active'.     $content = '<a data-drupal-link-system-path="other-page">Other page</a>';

    // Assert response with non-html content type gets ignored.     $response = new Response();
    $response->setContent($content);
    $response->headers->get('Content-Type', 'application/json');
    $subscriber->onResponse(new ResponseEvent(
      $this->prophesize(KernelInterface::class)->reveal(),
      $request_stack->getCurrentRequest(),
      HttpKernelInterface::MAIN_REQUEST,
      $response
    ));
    $this->assertSame($response->getContent()$content);
  }

  /** * Tests certain response types ignored by the ActiveLinkResponseFilter. * * @covers ::onResponse */
  
public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
        $this->cloner = new VarCloner();
        $this->cloner->setMaxItems(0);
        $this->cloner->addCasters(ReflectionCaster::UNSET_CLOSURE_FILE_INFO);
    }

    public function getContext(): ?array
    {
        if (null === $request = $this->requestStack->getCurrentRequest()) {
            return null;
        }

        $controller = $request->attributes->get('_controller');

        return [
            'uri' => $request->getUri(),
            'method' => $request->getMethod(),
            'controller' => $controller ? $this->cloner->cloneVar($controller) : $controller,
            'identifier' => spl_object_hash($request),
        ];
    }
$this->languageManager = $language_manager;
    $this->aliasManager = $alias_manager;
  }

  /** * {@inheritdoc} */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $entity_type,
      $container->get('entity_type.manager')->getStorage($entity_type->id()),
      $container->get('request_stack')->getCurrentRequest(),
      $container->get('form_builder'),
      $container->get('language_manager'),
      $container->get('path_alias.manager')
    );
  }

  /** * {@inheritdoc} */
  protected function getEntityIds() {
    $query = $this->getStorage()->getQuery()->accessCheck(TRUE);

    
/** * {@inheritdoc} */
  public static function getLabel() {
    return t('Protocol version');
  }

  /** * {@inheritdoc} */
  public function getContext() {
    return $this->requestStack->getCurrentRequest()->getProtocolVersion();
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}
$this->cacheBackend->set($this->cacheKey . ':' . $group_name$contextual_links);
      $this->pluginsByGroup[$group_name] = $contextual_links;
    }
    return $contextual_links;
  }

  /** * {@inheritdoc} */
  public function getContextualLinksArrayByGroup($group_name, array $route_parameters, array $metadata = []) {
    $links = [];
    $request = $this->requestStack->getCurrentRequest();
    foreach ($this->getContextualLinkPluginsByGroup($group_name) as $plugin_id => $plugin_definition) {
      /** @var \Drupal\Core\Menu\ContextualLinkInterface $plugin */
      $plugin = $this->createInstance($plugin_id);
      $route_name = $plugin->getRouteName();

      // Check access.       if (!$this->accessManager->checkNamedRoute($route_name$route_parameters$this->account)) {
        continue;
      }

      $links[$plugin_id] = [
        
private array $records = [];
    private array $errorCount = [];
    private ?RequestStack $requestStack;

    public function __construct(RequestStack $requestStack = null)
    {
        $this->requestStack = $requestStack;
    }

    private function doInvoke(array|LogRecord $record): array|LogRecord
    {
        $key = $this->requestStack && ($request = $this->requestStack->getCurrentRequest()) ? spl_object_id($request) : '';

        $timestampRfc3339 = false;
        if ($record['datetime'] instanceof \DateTimeInterface) {
            $timestamp = $record['datetime']->getTimestamp();
            $timestampRfc3339 = $record['datetime']->format(\DateTimeInterface::RFC3339_EXTENDED);
        } elseif (false !== $timestamp = strtotime($record['datetime'])) {
            $timestampRfc3339 = (new \DateTimeImmutable($record['datetime']))->format(\DateTimeInterface::RFC3339_EXTENDED);
        }

        $this->records[$key][] = [
            'timestamp' => $timestamp,
            


    /** * @see AbstractController::forward() */
    private function executeSubRequest(AppAction $action): string
    {
        try {
            $route = $this->router->match($action->getTargetUrl());

            /** @var Request $request */
            $request = $this->requestStack->getCurrentRequest();
            $subRequest = $request->duplicate(null, null, $route);

            $response = $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);

            return $response->getContent() ?: '';
        } catch (\Exception $e) {
            throw AppException::actionButtonProcessException($action->getActionId(), 'ActionButton local execution failed', $e);
        }
    }
}
/** * {@inheritdoc} */
  public static function getLabel() {
    return t('Path');
  }

  /** * {@inheritdoc} */
  public function getContext() {
    $request = $this->requestStack->getCurrentRequest();
    return $request->getBasePath() . $request->getPathInfo();
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}

  public function hasActiveWorkspace() {
    return $this->getActiveWorkspace() !== FALSE;
  }

  /** * {@inheritdoc} */
  public function getActiveWorkspace() {
    if (!isset($this->activeWorkspace)) {
      $request = $this->requestStack->getCurrentRequest();
      foreach ($this->negotiatorIds as $negotiator_id) {
        $negotiator = $this->classResolver->getInstanceFromDefinition($negotiator_id);
        if ($negotiator->applies($request)) {
          // By default, 'view' access is checked when a workspace is activated,           // but it should also be checked when retrieving the currently active           // workspace.           if (($negotiated_workspace = $negotiator->getActiveWorkspace($request)) && $negotiated_workspace->access('view')) {
            $active_workspace = $negotiated_workspace;
            break;
          }
        }
      }

    if (!empty($errors)) {
      throw new FileValidationException('File validation failed', $filename$errors);
    }

    // If we made it this far it's safe to record this file in the database.     $file->save();

    // Allow an anonymous user who creates a non-public file to see it. See     // \Drupal\file\FileAccessControlHandler::checkAccess().     if ($this->currentUser->isAnonymous() && $destinationScheme !== 'public') {
      $session = $this->requestStack->getCurrentRequest()->getSession();
      $allowed_temp_files = $session->get('anonymous_allowed_file_ids', []);
      $allowed_temp_files[$file->id()] = $file->id();
      $session->set('anonymous_allowed_file_ids', $allowed_temp_files);
    }

    return $result;
  }

  /** * Move the uploaded file from the temporary path to the destination. * * @todo Allows a sub-class to override this method in order to handle * raw file uploads in https://www.drupal.org/project/drupal/issues/2940383. * * @param \Drupal\file\Upload\UploadedFileInterface $uploadedFile * The uploaded file. * @param string $uri * The destination URI. * * @return bool * Returns FALSE if moving failed. * * @see https://www.drupal.org/project/drupal/issues/2940383 */
'installer.database-configuration' => 'database-configuration',
        'installer.database-import' => 'database-import',
        'installer.configuration' => 'configuration',
        'installer.finish' => 'finish',
    ];

    /** * @param array<string, mixed> $parameters */
    protected function renderInstaller(string $view, array $parameters = []): Response
    {
        $request = $this->container->get('request_stack')->getCurrentRequest();

        if ($request !== null) {
            $parameters['menu'] = $this->getMenuData($request);
        }

        /** @var ContainerInterface $container */
        $container = $this->container;

        if (!\array_key_exists('supportedLanguages', $parameters)) {
            /** @var array<string, string> $languages */
            $languages = $container->getParameter('shopware.installer.supportedLanguages');
            
Home | Imprint | This part of the site doesn't use cookies.