Skip to content

Commit

Permalink
Add Utils::redactUserInfo() method
Browse files Browse the repository at this point in the history
Co-Authored-By: Tim Düsterhus <209270+timwolla@users.noreply.github.com>
  • Loading branch information
GrahamCampbell and TimWolla committed Jul 18, 2024
1 parent 6de2986 commit 00f4536
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,13 @@ a message.
Read a line from the stream up to the maximum allowed buffer length.


## `GuzzleHttp\Psr7\Utils::redactUserInfo`

`public static function redactUserInfo(UriInterface $uri): UriInterface`

Redact the password in the user info part of a URI.


## `GuzzleHttp\Psr7\Utils::streamFor`

`public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface`
Expand Down
15 changes: 15 additions & 0 deletions src/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,21 @@ public static function readLine(StreamInterface $stream, ?int $maxLength = null)
return $buffer;
}


/**
* Redact the password in the user info part of a URI.
*/
public static function redactUserInfo(UriInterface $uri): UriInterface
{
$userInfo = $uri->getUserInfo();

if (false !== ($pos = \strpos($userInfo, ':'))) {
return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***');
}

return $uri;
}

/**
* Create a new stream based on the input type.
*
Expand Down
9 changes: 9 additions & 0 deletions tests/UtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,15 @@ public function testReadsLineUntilEmptyStringReturnedFromRead(): void
self::assertSame('h', Psr7\Utils::readLine($s));
}

public function testRedactUserInfoInUri(): void
{
$uri = new Psr7\Uri('http://my_user:secretPass@localhost/');

$redactedUri = Psr7\Utils::redactUserInfoInUri($uri);

self::assertSame('http://my_user:***@localhost/', (string) $redactedUri);
}

public function testCalculatesHash(): void
{
$s = Psr7\Utils::streamFor('foobazbar');
Expand Down

0 comments on commit 00f4536

Please sign in to comment.