getAbsoluteUrl example

$this->drupalGet('admin/modules');
    $this->submitForm(['modules[config_install_fail_test][enable]' => TRUE], 'Install');
    $this->assertSession()->responseContains('Unable to install Configuration install fail test, <em class="placeholder">config_test.dynamic.dotted.default, language/fr/config_test.dynamic.dotted.default</em> already exist in active configuration.');

    // Test installing a theme through the UI that has existing configuration.     // This relies on the fact the config_test has been installed and created     // the config_test.dynamic.dotted.default configuration and the translation     // override created still exists.     $this->drupalGet('admin/appearance');
    $url = $this->xpath("//a[contains(@href,'config_clash_test_theme') and contains(@href,'/install?')]/@href")[0];
    $this->drupalGet($this->getAbsoluteUrl($url->getText()));
    $this->assertSession()->responseContains('Unable to install config_clash_test_theme, <em class="placeholder">config_test.dynamic.dotted.default, language/fr/config_test.dynamic.dotted.default</em> already exist in active configuration.');

    // Test installing a theme through the API that has existing configuration.     try {
      \Drupal::service('theme_installer')->install(['config_clash_test_theme']);
      $this->fail('Expected PreExistingConfigException not thrown.');
    }
    catch (PreExistingConfigException $e) {
      $this->assertEquals('config_clash_test_theme', $e->getExtension());
      $this->assertEquals([StorageInterface::DEFAULT_COLLECTION => ['config_test.dynamic.dotted.default'], 'language.fr' => ['config_test.dynamic.dotted.default']]$e->getConfigObjects());
      $this->assertEquals('Configuration objects (config_test.dynamic.dotted.default, language/fr/config_test.dynamic.dotted.default) provided by config_clash_test_theme already exist in active configuration', $e->getMessage());
    }


    /** * Returns the absolute URL for the given absolute or relative path. * * This method returns the path unchanged if no request is available. * * @see Request::getUriForPath() */
    public function generateAbsoluteUrl(string $path): string
    {
        return $this->urlHelper->getAbsoluteUrl($path);
    }

    /** * Returns a relative path based on the current Request. * * This method returns the path unchanged if no request is available. * * @see Request::getRelativeUriForPath() */
    public function generateRelativePath(string $path): string
    {
        
/** * Sets a search page as the default in the UI. * * @param string $entity_id * The search page entity ID to enable. */
  protected function setDefaultThroughUi($entity_id) {
    $this->drupalGet('admin/config/search/pages');
    preg_match('|href="([^"]+' . $entity_id . '/set-default[^"]+)"|', $this->getSession()->getPage()->getContent()$matches);

    $this->drupalGet($this->getAbsoluteUrl($matches[1]));
  }

}

  protected function clickLinkWithXPath($xpath$arguments = []$index = 0) {
    $url_before = $this->getUrl();
    $urls = $this->xpath($xpath$arguments);
    if (isset($urls[$index])) {
      $url_target = $this->getAbsoluteUrl($urls[$index]->getAttribute('href'));
      return $this->drupalGet($url_target);
    }
    $this->fail(new FormattableMarkup('Link %label does not exist on @url_before', ['%label' => $xpath, '@url_before' => $url_before]));
    return FALSE;
  }

}
'width' => 120,
        'height' => 90,
        'upscale' => TRUE,
      ],
      'weight' => 0,
    ];

    $style->addImageEffect($effect);
    $style->save();
    $this->assertEquals('<img src="' . $url . '" width="120" height="60" alt="" loading="lazy" />', $this->getImageTag($variables));
    $this->assertFileDoesNotExist($generated_uri);
    $this->drupalGet($this->getAbsoluteUrl($url));
    $this->assertSession()->statusCodeEquals(200);
    $this->assertFileExists($generated_uri);
    $image_file = $image_factory->get($generated_uri);
    $this->assertEquals(120, $image_file->getWidth());
    $this->assertEquals(60, $image_file->getHeight());

    // Rotate 90 degrees anticlockwise.     $effect = [
      'id' => 'image_rotate',
      'data' => [
        'degrees' => -90,
        
$this->assertEquals(SAVED_UPDATED, $image_style->save());

    // Create a copy of a test image file in root.     $test_uri = 'public://image-test-do.png';
    \Drupal::service('file_system')->copy('core/tests/fixtures/files/image-test.png', $test_uri, FileSystemInterface::EXISTS_REPLACE);
    $this->assertFileExists($test_uri);

    // Execute the image style on the test image via a GET request.     $derivative_uri = 'public://styles/image_effect_test/public/image-test-do.png.jpeg';
    $this->assertFileDoesNotExist($derivative_uri);
    $url = \Drupal::service('file_url_generator')->transformRelative($image_style->buildUrl($test_uri));
    $this->drupalGet($this->getAbsoluteUrl($url));
    $this->assertSession()->statusCodeEquals(200);
    $this->assertFileExists($derivative_uri);
  }

}
parse_str($query_string$query_parts);
      $this->assertEquals($weight$query_parts['weight'], 'Found the expected weight query string.');

      // Create a random title for the block.       $title = $this->randomMachineName(8);
      $block_id = strtolower($this->randomMachineName(8));
      $edit = [
        'id' => $block_id,
        'settings[label]' => $title,
      ];
      // Create the block using the link parsed from the library page.       $this->drupalGet($this->getAbsoluteUrl($link->getAttribute('href')));
      $this->submitForm($edit, 'Save block');

      // Ensure that the block was created with the expected weight.       /** @var \Drupal\block\BlockInterface $block */
      $block = Block::load($block_id);
      $this->assertEquals($weight$block->getWeight(), 'Found the block with expected weight.');
    }
  }

  /** * Tests configuring and moving a module-define block to specific regions. */
else {
        $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
        // Path processing is needed for language prefixing. Skip it when a         // path that may look like an external URL is being used as internal.         $options['path_processing'] = !$force_internal;
        return Url::fromUri($uri$options)
          ->setAbsolute()
          ->toString();
      }
    }
    else {
      return $this->getAbsoluteUrl($path);
    }
  }

  /** * Takes a path and returns an absolute path. * * @param string $path * A path from the Mink controlled browser content. * * @return string * The $path with $base_url prepended, if necessary. */
'type' => 'entity_reference_label',
      ])
      ->save();

    // Create a user and then login.     $this->adminUser = $this->drupalCreateUser(['create article content']);
    $this->drupalLogin($this->adminUser);

    // Retrieve the autocomplete URL.     $this->drupalGet('node/add/article');
    $field = $this->assertSession()->fieldExists("{$this->fieldName}[0][target_id]");
    $this->autocompleteUrl = $this->getAbsoluteUrl($field->getAttribute('data-autocomplete-path'));
  }

  /** * Helper function for JSON formatted requests. * * @param string|\Drupal\Core\Url $path * Drupal path or URL to load into Mink controlled browser. * @param array $options * (optional) Options to be forwarded to the URL generator. * @param string[] $headers * (optional) An array containing additional HTTP request headers. * * @return string[] * Array representing decoded JSON response. */
$this->requestStack->push($transformedRequest);

        $context = $this->getContext($transformedRequest);
        $this->router->setContext($context);

        $absolutePath = $this->router->generate($case->route);
        $absoluteUrl = $this->router->generate($case->route, [], Router::ABSOLUTE_URL);
        $networkPath = $this->router->generate($case->route, [], Router::NETWORK_PATH);
        $pathInfo = $this->router->generate($case->route, [], Router::PATH_INFO);

        static::assertSame($case->getAbsolutePath()$absolutePathvar_export($case, true));
        static::assertSame($case->getAbsoluteUrl()$absoluteUrlvar_export($case, true));
        static::assertSame($case->getNetworkPath()$networkPathvar_export($case, true));
        static::assertSame($case->getPathInfo()$pathInfovar_export($case, true));

        $matches = $this->router->matchRequest($transformedRequest);
        static::assertEquals($case->route, $matches['_route']);

        $matches = $this->router->match($transformedRequest->getPathInfo());
        static::assertEquals($case->route, $matches['_route']);

        // test seo url generation         $host = $transformedRequest->attributes->get(RequestTransformer::SALES_CHANNEL_ABSOLUTE_BASE_URL)
            .
    \Drupal::service('cache.data')->deleteAll();
    \Drupal::service('cache.page')->deleteAll();
    $this->drupalGet('<front>');
    $session = $this->getSession();
    $page = $session->getPage();

    $style_elements = $page->findAll('xpath', '//link[@href and @rel="stylesheet"]');
    $this->assertNotEmpty($style_elements);
    $href = NULL;
    foreach ($style_elements as $element) {
      $href = $element->getAttribute('href');
      $url = $this->getAbsoluteUrl($href);
      // Not every script or style on a page is aggregated.       if (!str_contains($url$this->fileAssetsPath)) {
        continue;
      }
      $session = $this->getSession();
      $session->visit($url);
      $this->assertSession()->statusCodeEquals(200);
      $aggregate = $session = $session->getPage()->getContent();
      $this->assertStringContainsString('original-content', $aggregate);
      $this->assertStringNotContainsString('extra-stuff', $aggregate);
    }
    
/** * Asserts the aggregate header. * * @param string $url * The source URL. * @param bool $from_php * (optional) Is the result from PHP or disk? Defaults to TRUE (PHP). * @param string|null $content_type * The expected content type, or NULL to skip checking. */
  protected function assertAggregate(string $url, bool $from_php = TRUE, string $content_type = NULL): void {
    $url = $this->getAbsoluteUrl($url);
    if (!stripos($url$this->fileAssetsPath) !== FALSE) {
      return;
    }
    $session = $this->getSession();
    $session->visit($url);
    $this->assertSession()->statusCodeEquals(200);
    $headers = $session->getResponseHeaders();
    if (isset($content_type)) {
      $this->assertStringContainsString($content_type$headers['Content-Type'][0]);
    }
    if ($from_php) {
      
// Create a user with permission to view the actions administration pages     // and additionally permission to administer users. Otherwise the user would     // not be able to reference the anonymous user.     $this->drupalLogin($this->drupalCreateUser(['administer actions', 'administer users']));
    // Create AssignOwnerNode action.     $this->drupalGet('admin/config/system/actions');
    $this->submitForm(['action' => 'node_assign_owner_action'], 'Create');

    // Get the autocomplete URL of the owner_uid textfield.     $autocomplete_field = $this->getSession()->getPage()->findField('owner_uid');
    $autocomplete_url = $this->getAbsoluteUrl($autocomplete_field->getAttribute('data-autocomplete-path'));

    // Make sure that autocomplete works.     $user = $this->drupalCreateUser();
    $data = Json::decode($this->drupalGet($autocomplete_url['query' => ['q' => $user->getDisplayName(), '_format' => 'json']]));
    $this->assertNotEmpty($data);

    $anonymous = User::getAnonymousUser();
    // Ensure that the anonymous user exists.     $this->assertNotNull($anonymous);
    // Make sure the autocomplete does not show the anonymous user.     $data = Json::decode($this->drupalGet($autocomplete_url['query' => ['q' => $anonymous->getDisplayName(), '_format' => 'json']]));
    
class UrlHelperTest extends TestCase
{
    /** * @dataProvider getGenerateAbsoluteUrlData */
    public function testGenerateAbsoluteUrl($expected$path$pathinfo)
    {
        $stack = new RequestStack();
        $stack->push(Request::create($pathinfo));
        $helper = new UrlHelper($stack);

        $this->assertEquals($expected$helper->getAbsoluteUrl($path));
    }

    public static function getGenerateAbsoluteUrlData()
    {
        return [
            ['http://localhost/foo.png', '/foo.png', '/foo/bar.html'],
            ['http://localhost/foo/foo.png', 'foo.png', '/foo/bar.html'],
            ['http://localhost/foo/foo.png', 'foo.png', '/foo/bar'],
            ['http://localhost/foo/bar/foo.png', 'foo.png', '/foo/bar/'],

            ['http://example.com/baz', 'http://example.com/baz', '/'],
            [
$node1->save();
    $node2 = Node::create([
      'type' => $this->type,
      'title' => 'Foo Node',
    ]);
    $node2->save();

    // Try to add a new node and fill the entity reference field.     $this->drupalGet('node/add/' . $this->type);
    $field = $this->assertSession()->fieldExists('field_test_entity_ref_field[0][target_id]');
    $this->assertStringContainsString("/entity_reference_autocomplete/node/views/", $field->getAttribute('data-autocomplete-path'));
    $target_url = $this->getAbsoluteUrl($field->getAttribute('data-autocomplete-path'));
    $this->drupalGet($target_url['query' => ['q' => 'Foo']]);
    $this->assertSession()->pageTextContains($node1->getTitle() . ' (' . $node1->id() . ')');
    $this->assertSession()->pageTextContains($node2->getTitle() . ' (' . $node2->id() . ')');

    // Try to add a new node, fill the entity reference field and submit the     // form.     $this->drupalGet('node/add/' . $this->type);
    $this->submitForm([], 'Add another item');
    $edit = [
      'title[0][value]' => 'Example',
      'field_test_entity_ref_field[0][target_id]' => 'Foo Node (' . $node1->id() . ')',
      
Home | Imprint | This part of the site doesn't use cookies.