HttpExchangeFormatter::formatFullExchange()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 2
nop 0
1
<?php
2
3
namespace Rezzza\RestApiBehatExtension\Rest;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Psr\Http\Message\RequestInterface;
7
8
class HttpExchangeFormatter
9
{
10
    private $request;
11
12
    private $response;
13
14
    public function __construct(RequestInterface $request = null, ResponseInterface $response = null)
15
    {
16
        $this->request = $request;
17
        $this->response = $response;
18
    }
19
20
    public function formatRequest()
21
    {
22
        if (null === $this->request) {
23
            throw new \LogicException('You should send a request before printing it.');
24
        }
25
26
        return sprintf(
27
            "%s %s :\n%s%s\n",
28
            $this->request->getMethod(),
29
            $this->request->getUri(),
30
            $this->getRawHeaders($this->request->getHeaders()),
31
            $this->request->getBody()
32
        );
33
    }
34
35
    public function formatFullExchange()
36
    {
37
        if (null === $this->request || null === $this->response) {
38
            throw new \LogicException('You should send a request and store its response before printing them.');
39
        }
40
41
        return sprintf(
42
            "%s %s :\n%s %s\n%s%s\n",
43
            $this->request->getMethod(),
44
            $this->request->getUri()->__toString(),
45
            $this->response->getStatusCode(),
46
            $this->response->getReasonPhrase(),
47
            $this->getRawHeaders($this->response->getHeaders()),
48
            $this->response->getBody()
49
        );
50
    }
51
52
    /**
53
     * @param array $headers
54
     * @return string
55
     */
56
    private function getRawHeaders(array $headers)
57
    {
58
        $rawHeaders = '';
59
        foreach ($headers as $key => $value) {
60
            $rawHeaders .= sprintf("%s: %s\n", $key, is_array($value) ? implode(", ", $value) : $value);
61
        }
62
        $rawHeaders .= "\n";
63
64
        return $rawHeaders;
65
    }
66
}
67