Skip to content

Commit

Permalink
Merge pull request #71 from phil-davis/windows_host_handling
Browse files Browse the repository at this point in the history
Add empty host and trailing slash to windows file paths
  • Loading branch information
phil-davis authored Aug 17, 2022
2 parents 5145a08 + 290c896 commit 86e5e0e
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 4 deletions.
19 changes: 15 additions & 4 deletions lib/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,19 @@ function ($matches) {
$result = parse_url($uri);
if (!$result) {
$result = _parse_fallback($uri);
} else {
// Add empty host and trailing slash to Windows file paths
// file:///C:/path or file:///C:\path
// Note: the regex fragment [a-zA-Z]:[\/\\\\].* end up being
// [a-zA-Z]:[\/\\].*
// The 4 backslash in a row are the way to get 2 backslash into the actual string
// that is used as the regex. The 2 backslash are then the way to get 1 backslash
// character into the character set "a forward slash or a backslash"
if (isset($result['scheme']) && 'file' === $result['scheme'] && isset($result['path']) &&
preg_match('/^(?<windows_path> [a-zA-Z]:([\/\\\\].*)?)$/x', $result['path'])) {
$result['path'] = '/'.$result['path'];
$result['host'] = '';
}
}

return
Expand Down Expand Up @@ -341,15 +354,13 @@ function ($matches) {
$result['host'] = '';
} elseif ('//' === substr($uri, 0, 2)) {
// Uris that have an authority part.
$regex = '
%^
$regex = '%^
//
(?: (?<user> [^:@]+) (: (?<pass> [^@]+)) @)?
(?<host> ( [^:/]* | \[ [^\]]+ \] ))
(?: : (?<port> [0-9]+))?
(?<path> / .*)?
$%x
';
$%x';
if (!preg_match($regex, $uri, $matches)) {
throw new InvalidUriException('Invalid, or could not parse URI');
}
Expand Down
37 changes: 37 additions & 0 deletions tests/Uri/ParseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,43 @@ public function parseData(): array
'fragment' => null,
],
],
// Windows Paths
[
'file:///C:/path/file.ext',
[
'scheme' => 'file',
'host' => '',
'path' => '/C:/path/file.ext',
'port' => null,
'user' => null,
'query' => null,
'fragment' => null,
],
],
[
'file:///C:\path\file.ext',
[
'scheme' => 'file',
'host' => '',
'path' => '/C:\path\file.ext',
'port' => null,
'user' => null,
'query' => null,
'fragment' => null,
],
],
[
'file:///C:',
[
'scheme' => 'file',
'host' => '',
'path' => '/C:',
'port' => null,
'user' => null,
'query' => null,
'fragment' => null,
],
],
];
}
}
6 changes: 6 additions & 0 deletions tests/Uri/ResolveTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,12 @@ public function resolveData(): array
'0',
'http://example.org/0',
],
// Windows Paths
[
'file:///C:/path/file_a.ext',
'file_b.ext',
'file:///C:/path/file_b.ext',
],
];
}
}

0 comments on commit 86e5e0e

Please sign in to comment.