You are here

public function UrlTest::testDrupalParseUrl in Drupal 10

Same name and namespace in other branches
  1. 9 core/modules/system/tests/src/Kernel/Common/UrlTest.php \Drupal\Tests\system\Kernel\Common\UrlTest::testDrupalParseUrl()

Tests UrlHelper::parse().

File

core/modules/system/tests/src/Kernel/Common/UrlTest.php, line 221

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\Kernel\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
          ->assertEquals($expected, UrlHelper::parse($url), 'URL parsed correctly.');
      }
    }
  }

  // Relative URL that is known to confuse parse_url().
  $url = 'foo/bar:1';
  $result = [
    'path' => 'foo/bar:1',
    'query' => [],
    'fragment' => '',
  ];
  $this
    ->assertEquals($result, UrlHelper::parse($url), '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.');
}