|
@@ -0,0 +1,49 @@
|
|
1
|
+<?php
|
|
2
|
+namespace Tqdev\PhpCrudApi;
|
|
3
|
+
|
|
4
|
+use Psr\Http\Message\ResponseInterface;
|
|
5
|
+
|
|
6
|
+class ResponseUtils
|
|
7
|
+{
|
|
8
|
+ public static function output(ResponseInterface $response)
|
|
9
|
+ {
|
|
10
|
+ $status = $response->getStatusCode();
|
|
11
|
+ $headers = $response->getHeaders();
|
|
12
|
+ $body = $response->getBody()->getContents();
|
|
13
|
+
|
|
14
|
+ http_response_code($status);
|
|
15
|
+ foreach ($headers as $key => $values) {
|
|
16
|
+ foreach ($values as $value) {
|
|
17
|
+ header("$key: $value");
|
|
18
|
+ }
|
|
19
|
+ }
|
|
20
|
+ echo $body;
|
|
21
|
+ }
|
|
22
|
+
|
|
23
|
+ public static function addExceptionHeaders(ResponseInterface $response, \Throwable $e): ResponseInterface
|
|
24
|
+ {
|
|
25
|
+ $response = $response->withHeader('X-Exception-Name', get_class($e));
|
|
26
|
+ $response = $response->withHeader('X-Exception-Message', $e->getMessage());
|
|
27
|
+ $response = $response->withHeader('X-Exception-File', $e->getFile() . ':' . $e->getLine());
|
|
28
|
+ return $response;
|
|
29
|
+ }
|
|
30
|
+
|
|
31
|
+ public static function toString(ResponseInterface $response): string
|
|
32
|
+ {
|
|
33
|
+ $status = $response->getStatusCode();
|
|
34
|
+ $headers = $response->getHeaders();
|
|
35
|
+ $body = $response->getBody()->getContents();
|
|
36
|
+
|
|
37
|
+ $str = "$status\n";
|
|
38
|
+ foreach ($headers as $key => $values) {
|
|
39
|
+ foreach ($values as $value) {
|
|
40
|
+ $str .= "$key: $value\n";
|
|
41
|
+ }
|
|
42
|
+ }
|
|
43
|
+ if ($body !== '') {
|
|
44
|
+ $str .= "\n";
|
|
45
|
+ $str .= "$body\n";
|
|
46
|
+ }
|
|
47
|
+ return $str;
|
|
48
|
+ }
|
|
49
|
+}
|