1616use DateInterval , DateTimeInterface , RuntimeException , Throwable ;
1717use function array_map , explode , extension_loaded , function_exists , gzdecode , gzinflate , gzuncompress , implode ,
1818 in_array , json_decode , json_encode , rawurldecode , simplexml_load_string , sprintf , strtolower , trim ;
19- use const JSON_THROW_ON_ERROR ;
19+ use const JSON_PRETTY_PRINT , JSON_THROW_ON_ERROR , JSON_UNESCAPED_SLASHES ;
2020
2121/**
2222 *
@@ -68,7 +68,7 @@ public static function toString(MessageInterface $message, bool|null $appendBody
6868 '%s %s HTTP/%s ' ,
6969 $ message ->getMethod (),
7070 $ message ->getRequestTarget (),
71- $ message ->getProtocolVersion ()
71+ $ message ->getProtocolVersion (),
7272 );
7373
7474 if (!$ message ->hasHeader ('host ' )){
@@ -81,7 +81,7 @@ public static function toString(MessageInterface $message, bool|null $appendBody
8181 'HTTP/%s %s %s ' ,
8282 $ message ->getProtocolVersion (),
8383 $ message ->getStatusCode (),
84- $ message ->getReasonPhrase ()
84+ $ message ->getReasonPhrase (),
8585 );
8686 }
8787
@@ -97,6 +97,46 @@ public static function toString(MessageInterface $message, bool|null $appendBody
9797 return $ msg ;
9898 }
9999
100+ /**
101+ * Returns a JSON representation of an HTTP message.
102+ */
103+ public static function toJSON (MessageInterface $ message , bool |null $ appendBody = null ):string {
104+ $ appendBody ??= true ;
105+ $ msg = [];
106+
107+ if ($ message instanceof RequestInterface){
108+ $ msg ['request ' ] = [
109+ 'url ' => (string )$ message ->getUri (),
110+ 'method ' => $ message ->getMethod (),
111+ 'target ' => $ message ->getRequestTarget (),
112+ 'http ' => $ message ->getProtocolVersion (),
113+ ];
114+ }
115+ elseif ($ message instanceof ResponseInterface){
116+ $ msg ['response ' ] = [
117+ 'status ' => $ message ->getStatusCode (),
118+ 'reason ' => $ message ->getReasonPhrase (),
119+ 'http ' => $ message ->getProtocolVersion (),
120+ ];
121+ }
122+
123+ $ msg ['headers ' ] = [];
124+
125+ if ($ message instanceof RequestInterface && !$ message ->hasHeader ('host ' )){
126+ $ msg ['headers ' ]['Host ' ] = $ message ->getUri ()->getHost ();
127+ }
128+
129+ foreach ($ message ->getHeaders () as $ name => $ values ){
130+ $ msg ['headers ' ][$ name ] = implode (', ' , $ values );
131+ }
132+
133+ if ($ appendBody === true ){
134+ $ msg ['body ' ] = self ::getContents ($ message );
135+ }
136+
137+ return json_encode ($ msg , (JSON_THROW_ON_ERROR |JSON_PRETTY_PRINT |JSON_UNESCAPED_SLASHES ));
138+ }
139+
100140 /**
101141 * Decompresses the message content according to the Content-Encoding header and returns the decompressed data
102142 *
0 commit comments