1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace Link0\Bunq\Middleware; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Middleware; |
6
|
|
|
use GuzzleHttp\Promise\PromiseInterface; |
7
|
|
|
use Psr\Http\Message\RequestInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Be able to debug request and responses |
12
|
|
|
* |
13
|
|
|
* Usage: |
14
|
|
|
* $handlerStack->push(DebugMiddleware::tap(), 'debug_tap'); |
15
|
|
|
* |
16
|
|
|
* All requests and responses will now be printed to STDOUT |
17
|
|
|
* |
18
|
|
|
*/ |
19
|
|
|
final class DebugMiddleware |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @return \Closure |
23
|
|
|
*/ |
24
|
|
View Code Duplication |
public static function request() |
25
|
|
|
{ |
26
|
|
|
return function (RequestInterface $request) { |
27
|
|
|
echo chr(27) . '[33m' . "REQUEST: " . $request->getMethod() . ' ' . $request->getRequestTarget() . chr(27) . "[0m\n"; |
28
|
|
|
|
29
|
|
|
foreach ($request->getHeaders() as $key => $headers) { |
30
|
|
|
foreach ($headers as $header) { |
31
|
|
|
echo "${key}: ${header}\n"; |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
$body = (string) $request->getBody(); |
36
|
|
|
echo $body; |
37
|
|
|
$json = @json_decode($body, true); |
38
|
|
|
if ($json === null) { |
39
|
|
|
$json = []; |
40
|
|
|
} |
41
|
|
|
print_r($json); |
42
|
|
|
}; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @return \Closure |
47
|
|
|
*/ |
48
|
|
|
public static function response() |
49
|
|
|
{ |
50
|
|
View Code Duplication |
return function (RequestInterface $request, $options, PromiseInterface $responsePromise) { |
51
|
|
|
return $responsePromise->then(function (ResponseInterface $response) { |
52
|
|
|
echo chr(27) . '[33m' . "RESPONSE: HTTP/" . |
53
|
|
|
$response->getProtocolVersion() . ' ' . |
54
|
|
|
$response->getStatusCode() . ' ' . |
55
|
|
|
$response->getReasonPhrase() . chr(27) . "[0m\n"; |
56
|
|
|
|
57
|
|
|
foreach ($response->getHeaders() as $key => $headers) { |
58
|
|
|
foreach ($headers as $header) { |
59
|
|
|
echo "${key}: ${header}\n"; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$body = (string) $response->getBody(); |
64
|
|
|
$json = @json_decode($body, true); |
65
|
|
|
if ($json === null) { |
66
|
|
|
$json = []; |
67
|
|
|
} |
68
|
|
|
print_r($json); |
69
|
|
|
}); |
70
|
|
|
}; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @return callable |
75
|
|
|
*/ |
76
|
|
|
public static function tap(): callable |
77
|
|
|
{ |
78
|
|
|
return Middleware::tap( |
79
|
|
|
self::request(), |
80
|
|
|
self::response() |
81
|
|
|
); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|