1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace Link0\Bunq\Middleware; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Middleware; |
6
|
|
|
use GuzzleHttp\Promise\FulfilledPromise; |
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
|
|
|
return function (RequestInterface $request, $options, FulfilledPromise $responsePromise) { |
51
|
|
View Code Duplication |
$responsePromise->then(function (ResponseInterface $response) { |
52
|
|
|
echo chr(27) . '[33m' . "RESPONSE: HTTP/" . $response->getProtocolVersion() . ' ' . $response->getStatusCode() . ' ' . $response->getReasonPhrase() . chr(27) . "[0m\n"; |
53
|
|
|
|
54
|
|
|
foreach ($response->getHeaders() as $key => $headers) { |
55
|
|
|
foreach ($headers as $header) { |
56
|
|
|
echo "${key}: ${header}\n"; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$body = (string) $response->getBody(); |
61
|
|
|
$json = @json_decode($body, true); |
62
|
|
|
if ($json === null) { |
63
|
|
|
$json = []; |
64
|
|
|
} |
65
|
|
|
print_r($json); |
66
|
|
|
}); |
67
|
|
|
}; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return callable |
72
|
|
|
*/ |
73
|
|
|
public static function tap(): callable |
74
|
|
|
{ |
75
|
|
|
return Middleware::tap( |
76
|
|
|
self::request(), |
77
|
|
|
self::response() |
78
|
|
|
); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|