Completed
Push — master ( 3371e5...425c01 )
by Baptiste
11s
created

JsonAdapter   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
dl 0
loc 57
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A supports() 0 13 3
B introspect() 0 27 4
A __construct() 0 4 1
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
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, RequestInterface::class);
33
        }
34
35
        assert($message instanceof RequestInterface);
36
37
        // mandatory, clearing the line
38
        // todo : check how to clear without this echo...
39
        echo "\n";
40
41
        $dump = [
42
            'Request' => "{$message->getMethod()} {$message->getUri()}",
43
        ];
44
45
        foreach ($this->headers as $header) {
46
            $dump["Request {$header}"] = $message->getHeaderLine($header);
47
        }
48
49
        $body = (string) $message->getBody();
50
51
        if (!empty($body)) {
52
            $dump['Request 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 RequestInterface) {
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