Skip to content

Commit a37dc41

Browse files
committed
:octocat: added MessageUtil::toJSON()
1 parent fed28e2 commit a37dc41

File tree

2 files changed

+73
-3
lines changed

2 files changed

+73
-3
lines changed

src/MessageUtil.php

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
use DateInterval, DateTimeInterface, RuntimeException, Throwable;
1717
use 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
*

tests/MessageUtilTest.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use PHPUnit\Framework\TestCase;
1818
use RuntimeException;
1919
use function extension_loaded, file_get_contents, function_exists, sprintf, str_repeat;
20+
use function json_decode;
2021

2122
/**
2223
*
@@ -78,6 +79,35 @@ public function testMessageToString():void{
7879
);
7980
}
8081

82+
public function testMessageToJSON():void{
83+
$body = $this->streamFactory->createStream('testbody');
84+
85+
$request = $this->requestFactory
86+
->createRequest('GET', 'https://localhost/foo')
87+
->withAddedHeader('foo', 'bar')
88+
->withBody($body)
89+
;
90+
91+
$json = json_decode(MessageUtil::toJSON($request));
92+
93+
$this::assertSame('GET', $json->request->method);
94+
$this::assertSame('localhost', $json->headers->{'Host'});
95+
$this::assertSame('testbody', $json->body);
96+
97+
98+
$response = $this->responseFactory
99+
->createResponse()
100+
->withAddedHeader('foo', 'bar')
101+
->withBody($body)
102+
;
103+
104+
$json = json_decode(MessageUtil::toJSON($response));
105+
106+
$this::assertSame(200, $json->response->status);
107+
$this::assertSame('bar', $json->headers->{'foo'});
108+
$this::assertSame('testbody', $json->body);
109+
}
110+
81111
public static function decompressFnProvider():array{
82112
return [
83113
'br' => ['brotli_compress', 'br'],

0 commit comments

Comments
 (0)