requestStack example

$this->urlGenerator = \Drupal::urlGenerator();
  }

  /** * Tests the output process. */
  public function testProcessOutbound() {
    $expected_cacheability = (new BubbleableMetadata())
      ->addCacheContexts(['route'])
      ->setCacheMaxAge(Cache::PERMANENT);

    $request_stack = \Drupal::requestStack();
    /** @var \Symfony\Component\Routing\RequestContext $request_context */
    $request_context = \Drupal::service('router.request_context');

    // Test request with subdir on homepage.     $server = [
      'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => $this->root . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/subdir/', 'GET', [][][]$server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
    
$data[] = [
        'future_format' => '@interval hence',
        'past_format' => '@interval ago',
        'granularity' => $granularity,
      ];
    }

    foreach ($data as $settings) {
      $future_format = $settings['future_format'];
      $past_format = $settings['past_format'];
      $granularity = $settings['granularity'];
      $request_time = \Drupal::requestStack()->getCurrentRequest()->server->get('REQUEST_TIME');

      // Test a timestamp in the past       $value = $request_time - 87654321;
      $expected = new FormattableMarkup($past_format['@interval' => \Drupal::service('date.formatter')->formatTimeDiffSince($value['granularity' => $granularity])]);

      $component = $this->display->getComponent($this->fieldName);
      $component['type'] = 'timestamp_ago';
      $component['settings'] = $settings;
      $this->display->setComponent($this->fieldName, $component);

      $entity = EntityTest::create([]);
      


  /** * Tests the testRequestStack() method. * * @covers ::requestStack */
  public function testRequestStack() {
    $request_stack = new RequestStack();
    $this->setMockContainerService('request_stack', $request_stack);

    $this->assertSame($request_stack, \Drupal::requestStack());
  }

  /** * Tests the keyValue() method. * * @covers ::keyValue */
  public function testKeyValue() {
    $keyvalue = $this->getMockBuilder('Drupal\Core\KeyValueStore\KeyValueFactory')
      ->disableOriginalConstructor()
      ->getMock();
    
/** * Sets the current language. * * @param string $langcode * The langcode. The content language will be set to this using the * appropriate domain while the user language will be set to something * else so subsequent tests catch errors where the interface language * is used instead of the content language. */
  protected function setCurrentLanguage(string $langcode): void {
    \Drupal::requestStack()->push(Request::create("http://$langcode.book.test.domain/"));
    $language_manager = $this->container->get('language_manager');
    $language_manager->reset();
    $current_user = \Drupal::currentUser();
    $languages = $language_manager->getLanguages();
    unset($languages[$langcode]);
    $current_user->getAccount()->set('preferred_langcode', reset($languages)->getId());
    $this->assertNotSame($current_user->getPreferredLangcode()$langcode);
  }

  /** * Asserts a book item is correctly translated. * * @param array $item * A book tree item. * @param string $langcode * The language code for the requested translation. * * @internal */
// Test to make sure that we generated something for each token.     $this->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');

    foreach ($tests as $input => $expected) {
      $bubbleable_metadata = new BubbleableMetadata();
      $output = $this->tokenService->replace($input[]['langcode' => $this->interfaceLanguage->getId()]$bubbleable_metadata);
      $this->assertEquals($expected$outputnew FormattableMarkup('System site information token %token replaced.', ['%token' => $input]));
      $this->assertEquals($metadata_tests[$input]$bubbleable_metadata);
    }

    // Test [site:base-url] and [site:base-path] token with a subdirectory.     $request_stack = \Drupal::requestStack();
    // Test request with subdirectory on homepage.     $server = [
      'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => $this->root . '/subdir/index.php',
      'SERVER_NAME' => 'http://localhost',
    ];
    $request = Request::create('/subdir/', 'GET', [][][]$server);
    $request->server->add($server);
    $request_stack->push($request);
    $bubbleable_metadata = new BubbleableMetadata();
    $this->container->get('router.request_context')->setCompleteBaseUrl('http://localhost/subdir');
    
$this->installEntitySchema('menu_link_content');

    // Ensure that the weight of module_link_content is higher than system.     // @see menu_link_content_install()     module_set_weight('menu_link_content', 1);
  }

  /** * Tests bubbleable metadata of menu links' outbound route/path processing. */
  public function testOutboundPathAndRouteProcessing() {
    $request_stack = \Drupal::requestStack();
    /** @var \Symfony\Component\Routing\RequestContext $request_context */
    $request_context = \Drupal::service('router.request_context');

    $request = Request::create('/');
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
    $request_stack->push($request);
    $request_context->fromRequest($request);

    $menu_tree = \Drupal::menuTree();
    $renderer = \Drupal::service('renderer');

    
parent::setUp();

    $this->urlGenerator = \Drupal::urlGenerator();
  }

  /** * Tests the output process. */
  public function testProcessOutbound() {
    $expected_cacheability = (new BubbleableMetadata())->setCacheMaxAge(Cache::PERMANENT);

    $request_stack = \Drupal::requestStack();
    /** @var \Symfony\Component\Routing\RequestContext $request_context */
    $request_context = \Drupal::service('router.request_context');

    // Test request with subdir on homepage.     $server = [
      'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => $this->root . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/subdir', 'GET', [][][]$server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
    

  public function endQueryCapture() {
    $queries = Database::getLog('views');

    $this->additionalQueries = $queries;
  }

  public function renderPreview($display_id$args = []) {
    // Save the current path so it can be restored before returning from this function.     $request_stack = \Drupal::requestStack();
    $current_request = $request_stack->getCurrentRequest();
    $executable = $this->getExecutable();

    // Determine where the query and performance statistics should be output.     $config = \Drupal::config('views.settings');
    $show_query = $config->get('ui.show.sql_query.enabled');
    $show_info = $config->get('ui.show.preview_information');
    $show_location = $config->get('ui.show.sql_query.where');

    $show_stats = $config->get('ui.show.performance_statistics');
    if ($show_stats) {
      


  /** * Ensure page-front template suggestion is added when on front page. */
  public function testFrontPageThemeSuggestion() {
    // Set the current route to user.login because theme_get_suggestions() will     // query it to see if we are on the front page.     $request = Request::create('/user/login');
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'user.login');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/user/login'));
    \Drupal::requestStack()->push($request);
    $this->config('system.site')->set('page.front', '/user/login')->save();
    $suggestions = theme_get_suggestions(['user', 'login'], 'page');
    // Set it back to not annoy the batch runner.     \Drupal::requestStack()->pop();
    $this->assertContains('page__front', $suggestions, 'Front page template was suggested.');
  }

  /** * Tests theme can provide classes. */
  public function testClassLoading() {
    
/** * Sets up a request on the request stack with a specified format. * * @param string $format * The new request format. */
  protected function addRequestWithFormat($format) {
    $request = \Drupal::request();
    $request = clone $request;
    $request->setRequestFormat($format);

    \Drupal::requestStack()->push($request);
  }

  /** * Tests REST export with views render caching enabled. */
  public function testRestRenderCaching() {
    $this->drupalLogin($this->adminUser);
    /** @var \Drupal\Core\Render\RenderCacheInterface $render_cache */
    $render_cache = \Drupal::service('render_cache');

    // Enable render caching for the views.

  public function attachments() {
    \Drupal::state()->set('common_test.hook_page_attachments.early_rendering', TRUE);
    $build = [
      '#title' => 'A title',
      'content' => ['#markup' => 'Some content'],
    ];
    return \Drupal::service('main_content_renderer.html')->renderResponse($build, \Drupal::requestStack()->getCurrentRequest(), \Drupal::routeMatch());
  }

}
parent::setUp();
    $this->installConfig(['syslog']);
  }

  /** * @covers ::log */
  public function testSyslogWriting() {

    $request = Request::create('/page-not-found', 'GET', [][][]['REMOTE_ADDR' => '1.2.3.4']);
    $request->headers->set('Referer', 'other-site');
    \Drupal::requestStack()->push($request);

    $user = $this->getMockBuilder('Drupal\Core\Session\AccountInterface')->getMock();
    $user->method('id')->willReturn(42);
    $this->container->set('current_user', $user);

    \Drupal::logger('my_module')->warning('My warning message.', ['link' => '/my-link']);

    $log_filename = $this->container->get('file_system')->realpath('public://syslog.log');
    $logs = explode(PHP_EOL, file_get_contents($log_filename));
    $log = explode('|', $logs[0]);

    
$_SERVER['SERVER_SOFTWARE'] = NULL;
    $_SERVER['SERVER_NAME'] = $host;
    $_SERVER['REQUEST_URI'] = '/';
    $_SERVER['REQUEST_METHOD'] = 'GET';
    $_SERVER['SCRIPT_NAME'] = '/index.php';
    $_SERVER['SCRIPT_FILENAME'] = '/index.php';
    $_SERVER['PHP_SELF'] = '/index.php';
    $_SERVER['HTTP_USER_AGENT'] = 'Drupal command line';
    $_SERVER['HTTPS'] = $https;

    $request = Request::createFromGlobals();
    \Drupal::requestStack()->push($request);

    $this->assertSame($expected, \Drupal::service('file_url_generator')->transformRelative($url));
  }

  public function providerFileUrlTransformRelative() {
    $data = [
      'http' => [
        'example.com',
        80,
        '',
        'http://example.com/page',
        
public function test24() {
    $this->removeExceptionLogger();
    throw new \Exception('Escaped content: <p> <br> <h3>');
  }

  public function test25() {
    return [
      '#cache' => [
        'url',
      ],
      '#markup' => \Drupal::requestStack()->getCurrentRequest()->getUri(),
    ];
  }

  public function testRouteName(Request $request) {
    return [
      '#markup' => $request->attributes->get(RouteObjectInterface::ROUTE_NAME),
    ];
  }

  /** * Throws an exception. * * @param string $message * The message to use in the exception. * * @throws \Exception * Always thrown. */
public function test40xThemeSuggestions(int $httpCode, string $suggestion): void {
    $path_matcher = $this->prophesize(PathMatcherInterface::class);
    $path_matcher->isFrontPage()->willReturn(FALSE);
    \Drupal::getContainer()->set('path.matcher', $path_matcher->reveal());

    $path_current = $this->prophesize(CurrentPathStack::class);
    $path_current->getPath()->willReturn('/node/123');
    \Drupal::getContainer()->set('path.current', $path_current->reveal());

    $exception = $this->prophesize(HttpExceptionInterface::class);
    $exception->getStatusCode()->willReturn($httpCode);
    \Drupal::requestStack()->getCurrentRequest()->attributes->set('exception', $exception->reveal());

    $suggestions = \Drupal::moduleHandler()->invokeAll('theme_suggestions_page', [[]]);
    $this->assertSame([
      'page__node',
      'page__node__%',
      'page__node__123',
      'page__4xx',
      $suggestion,
    ]$suggestions);
  }

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