Skip to content

Commit

Permalink
comfortable multibytes cutoff, ref guzzle#588
Browse files Browse the repository at this point in the history
  • Loading branch information
TheNorthMemory committed Dec 23, 2023
1 parent 45b30f9 commit a46f32e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,25 @@ public static function bodySummary(MessageInterface $message, int $truncateAt =
return null;
}

do {
$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] || ($bin[0] && $bin[1])) {
$body->rewind();
break;
}
$truncateAt -= 1;
} while ($bin[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

0 comments on commit a46f32e

Please sign in to comment.