Passed
Pull Request — master (#46)
by Baptiste
02:41
created

JsonAdapter::supports()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
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
final class JsonAdapter implements Adapter
13
{
14
    public function introspect(MessageInterface $message, array $headers): void
15
    {
16
        if (!$this->supports($message)) {
17
            throw new UnsupportedMessage($message, ResponseInterface::class);
18
        }
19
20
        // mandatory, clearing the line
21
        // todo : check how to clear without this echo...
22
        echo "\n";
23
24
        $dump = [
25
            'Response Status' => "{$message->getStatusCode()} {$message->getReasonPhrase()}",
26
        ];
27
28
        foreach ($headers as $header) {
29
            $dump["Response {$header}"] = $message->getHeaderLine($header);
30
        }
31
32
        $body = (string) $message->getBody();
33
34
        if (!empty($body)) {
35
            $dump['Response Body'] = json_decode($body);
36
        }
37
38
        VarDumper::dump($dump);
39
    }
40
41
    public function supports(MessageInterface $message): bool
42
    {
43
        if (!class_exists(VarDumper::class)) {
44
            return false;
45
        }
46
47
        if (!$message instanceof ResponseInterface) {
48
            return false;
49
        }
50
51
        [$contentType,] = explode(';', $message->getHeaderLine('Content-Type'), 2);
52
53
        return 'application/json' === $contentType;
54
    }
55
}
56