1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace 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
|
|
|
* @author Dennis de Greef |
12
|
|
|
* |
13
|
|
|
* Be able to debug request and responses |
14
|
|
|
* |
15
|
|
|
* Usage: |
16
|
|
|
* $handlerStack->push(DebugMiddleware::tap(), 'debug_tap'); |
17
|
|
|
* |
18
|
|
|
* All requests and responses will now be printed to STDOUT |
19
|
|
|
* |
20
|
|
|
*/ |
21
|
|
|
final class DebugMiddleware |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @return \Closure |
25
|
|
|
*/ |
26
|
|
View Code Duplication |
public static function request() |
|
|
|
|
27
|
|
|
{ |
28
|
|
|
return function (RequestInterface $request) { |
29
|
|
|
echo chr(27) . '[33m' . "REQUEST: " . $request->getMethod() . ' ' . $request->getRequestTarget() . chr( |
30
|
|
|
27 |
31
|
|
|
) . "[0m\n"; |
32
|
|
|
|
33
|
|
|
foreach ($request->getHeaders() as $key => $headers) { |
34
|
|
|
foreach ($headers as $header) { |
35
|
|
|
echo "${key}: ${header}\n"; |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
$body = (string)$request->getBody(); |
40
|
|
|
echo $body; |
41
|
|
|
$json = @json_decode($body, true); |
42
|
|
|
if ($json === null) { |
43
|
|
|
$json = []; |
44
|
|
|
} |
45
|
|
|
print_r($json); |
46
|
|
|
}; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @return \Closure |
51
|
|
|
*/ |
52
|
|
|
public static function response() |
53
|
|
|
{ |
54
|
|
|
return function (RequestInterface $request, $options, FulfilledPromise $responsePromise) { |
55
|
|
|
$responsePromise->then( |
56
|
|
View Code Duplication |
function (ResponseInterface $response) { |
|
|
|
|
57
|
|
|
echo chr(27) . '[33m' . "RESPONSE: HTTP/" . $response->getProtocolVersion() . ' ' . $response->getStatusCode() . ' ' . $response->getReasonPhrase() . chr(27) . "[0m\n"; |
58
|
|
|
|
59
|
|
|
foreach ($response->getHeaders() as $key => $headers) { |
60
|
|
|
foreach ($headers as $header) { |
61
|
|
|
echo "${key}: ${header}\n"; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$body = (string)$response->getBody(); |
66
|
|
|
$json = @json_decode($body, true); |
67
|
|
|
if ($json === null) { |
68
|
|
|
$json = []; |
69
|
|
|
} |
70
|
|
|
print_r($json); |
71
|
|
|
} |
72
|
|
|
); |
73
|
|
|
}; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @return callable |
78
|
|
|
*/ |
79
|
|
|
public static function tap() |
80
|
|
|
{ |
81
|
|
|
return Middleware::tap( |
82
|
|
|
self::request(), |
83
|
|
|
self::response() |
84
|
|
|
); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.