Skip to content

Commit 64b7082

Browse files
committed
:octocat: make sure we rewind the message body
1 parent 4d1b1ff commit 64b7082

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

src/MessageUtil.php

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,23 +21,29 @@
2121
class MessageUtil{
2222

2323
/**
24-
* @return \stdClass|array|bool
24+
* Read the message body's content and make sure we rewind
2525
*/
26-
public static function decodeJSON(MessageInterface $message, bool $assoc = null){
27-
$data = json_decode((string)$message->getBody(), $assoc ?? false);
28-
29-
$message->getBody()->rewind();
26+
protected static function getContents(MessageInterface $message):string{
27+
$body = $message->getBody();
28+
$body->rewind(); //rewind before read...
29+
$data = $body->getContents();
30+
$body->rewind(); // ...and after
3031

3132
return $data;
3233
}
3334

35+
/**
36+
* @return \stdClass|array|bool
37+
*/
38+
public static function decodeJSON(MessageInterface $message, bool $assoc = null){
39+
return json_decode(self::getContents($message), $assoc ?? false);
40+
}
41+
3442
/**
3543
* @return \SimpleXMLElement|array|bool
3644
*/
3745
public static function decodeXML(MessageInterface $message, bool $assoc = null){
38-
$data = simplexml_load_string((string)$message->getBody());
39-
40-
$message->getBody()->rewind();
46+
$data = simplexml_load_string(self::getContents($message));
4147

4248
return $assoc === true
4349
? json_decode(json_encode($data), true) // cruel
@@ -68,10 +74,7 @@ public static function toString(MessageInterface $message, bool $appendBody = tr
6874

6975
// appending the body might cause issues in some cases, e.g. with large responses or file streams
7076
if($appendBody){
71-
$data = $message->getBody()->getContents();
72-
$message->getBody()->rewind();
73-
74-
$msg .= "\r\n\r\n".$data;
77+
$msg .= "\r\n\r\n".self::getContents($message);
7578
}
7679

7780
return $msg;
@@ -87,9 +90,8 @@ public static function toString(MessageInterface $message, bool $appendBody = tr
8790
* @throws \RuntimeException
8891
*/
8992
public static function decompress(MessageInterface $message):string{
90-
$data = $message->getBody()->getContents();
93+
$data = self::getContents($message);
9194
$encoding = strtolower($message->getHeaderLine('content-encoding'));
92-
$message->getBody()->rewind();
9395

9496
if($encoding === '' || $encoding === 'identity'){
9597
return $data;

0 commit comments

Comments
 (0)