You are here

public function UrlTest::testExternalUrls in Drupal 8

Tests external URL handling.

File

core/modules/system/tests/src/Functional/Common/UrlTest.php, line 296

Class

UrlTest
Confirm that \Drupal\Core\Url, \Drupal\Component\Utility\UrlHelper::filterQueryParameters(), \Drupal\Component\Utility\UrlHelper::buildQuery(), and \Drupal\Core\Utility\LinkGeneratorInterface::generate() work correctly with various input.

Namespace

Drupal\Tests\system\Functional\Common

Code

public function testExternalUrls() {
  $test_url = 'https://www.drupal.org/';

  // Verify external URL can contain a fragment.
  $url = $test_url . '#drupal';
  $result = Url::fromUri($url)
    ->toString();
  $this
    ->assertEqual($url, $result, 'External URL with fragment works without a fragment in $options.');

  // Verify fragment can be overridden in an external URL.
  $url = $test_url . '#drupal';
  $fragment = $this
    ->randomMachineName(10);
  $result = Url::fromUri($url, [
    'fragment' => $fragment,
  ])
    ->toString();
  $this
    ->assertEqual($test_url . '#' . $fragment, $result, 'External URL fragment is overridden with a custom fragment in $options.');

  // Verify external URL can contain a query string.
  $url = $test_url . '?drupal=awesome';
  $result = Url::fromUri($url)
    ->toString();
  $this
    ->assertEqual($url, $result);

  // Verify external URL can contain a query string with an integer key.
  $url = $test_url . '?120=1';
  $result = Url::fromUri($url)
    ->toString();
  $this
    ->assertEqual($url, $result);

  // Verify external URL can be extended with a query string.
  $url = $test_url;
  $query = [
    'awesome' => 'drupal',
  ];
  $result = Url::fromUri($url, [
    'query' => $query,
  ])
    ->toString();
  $this
    ->assertSame('https://www.drupal.org/?awesome=drupal', $result);

  // Verify query string can be extended in an external URL.
  $url = $test_url . '?drupal=awesome';
  $query = [
    'awesome' => 'drupal',
  ];
  $result = Url::fromUri($url, [
    'query' => $query,
  ])
    ->toString();
  $this
    ->assertEqual('https://www.drupal.org/?drupal=awesome&awesome=drupal', $result);
}