You are here

public function UrlTest::testDrupalParseUrl in Drupal 8

Tests UrlHelper::parse().

File

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

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 testDrupalParseUrl() {

  // Relative, absolute, and external URLs, without/with explicit script path,
  // without/with Drupal path.
  foreach ([
    '',
    '/',
    'https://www.drupal.org/',
  ] as $absolute) {
    foreach ([
      '',
      'index.php/',
    ] as $script) {
      foreach ([
        '',
        'foo/bar',
      ] as $path) {
        $url = $absolute . $script . $path . '?foo=bar&bar=baz&baz#foo';
        $expected = [
          'path' => $absolute . $script . $path,
          'query' => [
            'foo' => 'bar',
            'bar' => 'baz',
            'baz' => '',
          ],
          'fragment' => 'foo',
        ];
        $this
          ->assertEqual(UrlHelper::parse($url), $expected, 'URL parsed correctly.');
      }
    }
  }

  // Relative URL that is known to confuse parse_url().
  $url = 'foo/bar:1';
  $result = [
    'path' => 'foo/bar:1',
    'query' => [],
    'fragment' => '',
  ];
  $this
    ->assertEqual(UrlHelper::parse($url), $result, 'Relative URL parsed correctly.');

  // Test that drupal can recognize an absolute URL. Used to prevent attack vectors.
  $url = 'https://www.drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
  $this
    ->assertTrue(UrlHelper::isExternal($url), 'Correctly identified an external URL.');

  // Test that UrlHelper::parse() does not allow spoofing a URL to force a malicious redirect.
  $parts = UrlHelper::parse('forged:http://cwe.mitre.org/data/definitions/601.html');
  $this
    ->assertFalse(UrlHelper::isValid($parts['path'], TRUE), '\\Drupal\\Component\\Utility\\UrlHelper::isValid() correctly parsed a forged URL.');
}