function UrlTest::testDrupalParseUrl

Same name in other branches
  1. 9 core/modules/system/tests/src/Kernel/Common/UrlTest.php \Drupal\Tests\system\Kernel\Common\UrlTest::testDrupalParseUrl()
  2. 8.9.x core/modules/system/tests/src/Functional/Common/UrlTest.php \Drupal\Tests\system\Functional\Common\UrlTest::testDrupalParseUrl()
  3. 11.x 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 224

Class

UrlTest
Tests the Url object.

Namespace

Drupal\Tests\system\Kernel\Common

Code

public function testDrupalParseUrl() : void {
    // 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.example.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.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.