Skip to content

Commit

Permalink
Merge pull request #41 from akrabat/encode-user-info
Browse files Browse the repository at this point in the history
Encode user info
  • Loading branch information
silentworks authored Nov 3, 2017
2 parents 37e80cc + 70921a5 commit fd70c08
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/Uri.php
Original file line number Diff line number Diff line change
Expand Up @@ -353,12 +353,31 @@ public function getUserInfo()
public function withUserInfo($user, $password = null)
{
$clone = clone $this;
$clone->user = $user;
$clone->password = $password ? $password : '';
$clone->user = $this->filterUserInfo($user);
if ($clone->user) {
$clone->password = $password ? $this->filterUserInfo($password) : '';
}

return $clone;
}

/**
* Filters the user info string.
*
* @param string $query The raw uri query string.
* @return string The percent-encoded query string.
*/
protected function filterUserInfo($query)
{
return preg_replace_callback(
'/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=]+|%(?![A-Fa-f0-9]{2}))/u',
function ($match) {
return rawurlencode($match[0]);
},
$query
);
}

/**
* Retrieve the host component of the URI.
*
Expand Down
15 changes: 15 additions & 0 deletions tests/UriTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,13 @@ public function testGetUserInfoWithUsernameAndPassword()
$this->assertEquals('josh:sekrit', $uri->getUserInfo());
}

public function testGetUserInfoWithUsernameAndPasswordEncodesCorrectly()
{
$uri = Uri::createFromString('https://bob%40example.com:pass%3Aword@example.com:443/foo/bar?abc=123#section3');

$this->assertEquals('bob%40example.com:pass%3Aword', $uri->getUserInfo());
}

public function testGetUserInfoWithUsername()
{
$uri = Uri::createFromString('http://josh@example.com/foo/bar?abc=123#section3');
Expand All @@ -136,6 +143,14 @@ public function testWithUserInfo()
$this->assertAttributeEquals('pass', 'password', $uri);
}

public function testWithUserInfoEncodesCorrectly()
{
$uri = $this->uriFactory()->withUserInfo('bob@example.com', 'pass:word');

$this->assertAttributeEquals('bob%40example.com', 'user', $uri);
$this->assertAttributeEquals('pass%3Aword', 'password', $uri);
}

public function testWithUserInfoRemovesPassword()
{
$uri = $this->uriFactory()->withUserInfo('bob');
Expand Down

0 comments on commit fd70c08

Please sign in to comment.