Skip to content

Commit

Permalink
[2.7] Add Utils::redactUserInfo() method (#613)
Browse files Browse the repository at this point in the history
* Add `Utils::redactUserInfo()` method

Co-Authored-By: Tim Düsterhus <209270+timwolla@users.noreply.github.com>

* Update Utils.php

---------

Co-authored-by: Tim Düsterhus <209270+timwolla@users.noreply.github.com>
  • Loading branch information
GrahamCampbell and TimWolla authored Jul 18, 2024
1 parent 6de2986 commit 9aed204
Show file tree
Hide file tree
Showing 3 changed files with 30 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
14 changes: 14 additions & 0 deletions src/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,20 @@ 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 testRedactUserInfo(): void
{
$uri = new Psr7\Uri('http://my_user:secretPass@localhost/');

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

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

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

0 comments on commit 9aed204

Please sign in to comment.