21
21
class MessageUtil{
22
22
23
23
/**
24
- * @return \stdClass|array|bool
24
+ * Read the message body's content and make sure we rewind
25
25
*/
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
30
31
31
32
return $ data ;
32
33
}
33
34
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
+
34
42
/**
35
43
* @return \SimpleXMLElement|array|bool
36
44
*/
37
45
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 ));
41
47
42
48
return $ assoc === true
43
49
? json_decode (json_encode ($ data ), true ) // cruel
@@ -68,10 +74,7 @@ public static function toString(MessageInterface $message, bool $appendBody = tr
68
74
69
75
// appending the body might cause issues in some cases, e.g. with large responses or file streams
70
76
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 );
75
78
}
76
79
77
80
return $ msg ;
@@ -87,9 +90,8 @@ public static function toString(MessageInterface $message, bool $appendBody = tr
87
90
* @throws \RuntimeException
88
91
*/
89
92
public static function decompress (MessageInterface $ message ):string {
90
- $ data = $ message -> getBody ()-> getContents ();
93
+ $ data = self :: getContents ($ message );
91
94
$ encoding = strtolower ($ message ->getHeaderLine ('content-encoding ' ));
92
- $ message ->getBody ()->rewind ();
93
95
94
96
if ($ encoding === '' || $ encoding === 'identity ' ){
95
97
return $ data ;
0 commit comments