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

JsonAdapter::introspect()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 25
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 5
nop 2
dl 0
loc 25
rs 8.5806
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
namespace Behapi\Debug\Introspection\Request\VarDumper;
3
4
use Psr\Http\Message\MessageInterface;
5
use Psr\Http\Message\RequestInterface;
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, RequestInterface::class);
18
        }
19
20
        // mandatory, clearing the line
21
        // todo : check how to clear without this echo...
22
        echo "\n";
23
24
        $dump = [
25
            'Request' => "{$message->getMethod()} {$message->getUri()}",
26
        ];
27
28
        foreach ($headers as $header) {
29
            $dump["Request {$header}"] = $message->getHeaderLine($header);
30
        }
31
32
        $body = (string) $message->getBody();
33
34
        if (!empty($body)) {
35
            $dump['Request 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 RequestInterface) {
48
            return false;
49
        }
50
51
        [$contentType,] = explode(';', $message->getHeaderLine('Content-Type'), 2);
52
53
        return 'application/json' === $contentType;
54
    }
55
}
56