|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
namespace Behapi\Debug\Introspection\Response\VarDumper; |
|
3
|
|
|
|
|
4
|
|
|
use Psr\Http\Message\MessageInterface; |
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
6
|
|
|
|
|
7
|
|
|
use Symfony\Component\VarDumper\VarDumper; |
|
8
|
|
|
|
|
9
|
|
|
use Behapi\Debug\Introspection\Adapter; |
|
10
|
|
|
use Behapi\Debug\Introspection\UnsupportedMessage; |
|
11
|
|
|
|
|
12
|
|
|
use function in_array; |
|
13
|
|
|
|
|
14
|
|
|
final class JsonAdapter implements Adapter |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var iterable<string> */ |
|
17
|
|
|
private $headers; |
|
18
|
|
|
|
|
19
|
|
|
/** @var string[] */ |
|
20
|
|
|
private $types; |
|
21
|
|
|
|
|
22
|
|
|
/** @param iterable<string> $headers */ |
|
23
|
|
|
public function __construct(iterable $headers, array $types) |
|
24
|
|
|
{ |
|
25
|
|
|
$this->types = $types; |
|
26
|
|
|
$this->headers = $headers; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function introspect(MessageInterface $message): void |
|
30
|
|
|
{ |
|
31
|
|
|
if (!$this->supports($message)) { |
|
32
|
|
|
throw new UnsupportedMessage($message, ResponseInterface::class); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
assert($message instanceof ResponseInterface); |
|
36
|
|
|
|
|
37
|
|
|
// mandatory, clearing the line |
|
38
|
|
|
// todo : check how to clear without this echo... |
|
39
|
|
|
echo "\n"; |
|
40
|
|
|
|
|
41
|
|
|
$dump = [ |
|
42
|
|
|
'Response Status' => "{$message->getStatusCode()} {$message->getReasonPhrase()}", |
|
43
|
|
|
]; |
|
44
|
|
|
|
|
45
|
|
|
foreach ($this->headers as $header) { |
|
46
|
|
|
$dump["Response {$header}"] = $message->getHeaderLine($header); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
$body = (string) $message->getBody(); |
|
50
|
|
|
|
|
51
|
|
|
if (!empty($body)) { |
|
52
|
|
|
$dump['Response Body'] = json_decode($body); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
VarDumper::dump($dump); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function supports(MessageInterface $message): bool |
|
59
|
|
|
{ |
|
60
|
|
|
if (!class_exists(VarDumper::class)) { |
|
61
|
|
|
return false; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
if (!$message instanceof ResponseInterface) { |
|
65
|
|
|
return false; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
[$contentType,] = explode(';', $message->getHeaderLine('Content-Type'), 2); |
|
69
|
|
|
|
|
70
|
|
|
return in_array($contentType, $this->types, true); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|