2121class 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