Skip to content

Commit 9aed204

Browse files
[2.7] Add Utils::redactUserInfo() method (#613)
* 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>
1 parent 6de2986 commit 9aed204

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

README.md

+7
Original file line numberDiff line numberDiff line change
@@ -503,6 +503,13 @@ a message.
503503
Read a line from the stream up to the maximum allowed buffer length.
504504

505505

506+
## `GuzzleHttp\Psr7\Utils::redactUserInfo`
507+
508+
`public static function redactUserInfo(UriInterface $uri): UriInterface`
509+
510+
Redact the password in the user info part of a URI.
511+
512+
506513
## `GuzzleHttp\Psr7\Utils::streamFor`
507514

508515
`public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface`

src/Utils.php

+14
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,20 @@ public static function readLine(StreamInterface $stream, ?int $maxLength = null)
250250
return $buffer;
251251
}
252252

253+
/**
254+
* Redact the password in the user info part of a URI.
255+
*/
256+
public static function redactUserInfo(UriInterface $uri): UriInterface
257+
{
258+
$userInfo = $uri->getUserInfo();
259+
260+
if (false !== ($pos = \strpos($userInfo, ':'))) {
261+
return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***');
262+
}
263+
264+
return $uri;
265+
}
266+
253267
/**
254268
* Create a new stream based on the input type.
255269
*

tests/UtilsTest.php

+9
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,15 @@ public function testReadsLineUntilEmptyStringReturnedFromRead(): void
154154
self::assertSame('h', Psr7\Utils::readLine($s));
155155
}
156156

157+
public function testRedactUserInfo(): void
158+
{
159+
$uri = new Psr7\Uri('http://my_user:secretPass@localhost/');
160+
161+
$redactedUri = Psr7\Utils::redactUserInfo($uri);
162+
163+
self::assertSame('http://my_user:***@localhost/', (string) $redactedUri);
164+
}
165+
157166
public function testCalculatesHash(): void
158167
{
159168
$s = Psr7\Utils::streamFor('foobazbar');

0 commit comments

Comments
 (0)