Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2.8] Summarize the multibytes body stream comfortable #589

Open
wants to merge 2 commits into
base: 2.7
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,28 @@ public static function bodySummary(MessageInterface $message, int $truncateAt =
return null;
}

do {
if ($size < $truncateAt) {
break;
}
$body->rewind();
$body->seek($truncateAt);
$char = $body->read(1);
$bin = str_pad(base_convert(strval(ord($char)), 10, 2), 8, '0', STR_PAD_LEFT);
// detect the character binary conversion
// stoped at 0x00000000 - 0x0000007F or the first byte of the utf8 code points
// @see https://man7.org/linux/man-pages/man7/utf-8.7.html
if ($bin[0] === '0' || ($bin[0] === '1' && $bin[1] === '1')) {
$body->rewind();
break;
}
--$truncateAt;
} while ($bin[0] !== '0');
// fast return while won't need reading the stream
if ($truncateAt === 0) {
return null;
}

$body->rewind();
$summary = $body->read($truncateAt);
$body->rewind();
Expand Down
10 changes: 10 additions & 0 deletions tests/MessageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,16 @@ public function testMessageBodySummaryWithSpecialUTF8Characters(): void
self::assertSame('’é€௵ဪ‱', Psr7\Message::bodySummary($message));
}

public function testMessageBodySummaryWithComfortableUTF8Characters(): void
{
$message = new Psr7\Response(200, [], '必填性规则校验失败,此字段为必填项');
$wellformed = '必填性规则校验失 (truncated...)';
// One chinese character is three bytes in the utf8 character range.
self::assertSame($wellformed, Psr7\Message::bodySummary($message, 24));
self::assertSame($wellformed, Psr7\Message::bodySummary($message, 25));
self::assertSame($wellformed, Psr7\Message::bodySummary($message, 26));
}

public function testMessageBodySummaryWithSpecialUTF8CharactersAndLargeBody(): void
{
$message = new Psr7\Response(200, [], '🤦🏾‍♀️');
Expand Down