Skip to content

Commit 00f4536

Browse files
Add Utils::redactUserInfo() method
Co-Authored-By: Tim Düsterhus <209270+timwolla@users.noreply.github.com>
1 parent 6de2986 commit 00f4536

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-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

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

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

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 testRedactUserInfoInUri(): void
158+
{
159+
$uri = new Psr7\Uri('http://my_user:secretPass@localhost/');
160+
161+
$redactedUri = Psr7\Utils::redactUserInfoInUri($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)