Completed
Push — master ( d40614...680e53 )
by Sébastien
10s
created

HttpExchangeFormatter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
nc 1
cc 1
eloc 3
nop 2
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, ResponseInterface $response)
15
    {
16
        $this->request = $request;
17
        $this->response = $response;
18
    }
19
20
    public function formatRequest()
21
    {
22
        return sprintf(
23
            "%s %s :\n%s%s\n",
24
            $this->request->getMethod(),
25
            $this->request->getUri(),
26
            $this->getRawHeaders($this->request->getHeaders()),
27
            $this->request->getBody()
28
        );
29
    }
30
31
    public function formatFullExchange()
32
    {
33
        return sprintf(
34
            "%s %s :\n%s %s\n%s%s\n",
35
            $this->request->getMethod(),
36
            $this->request->getUri()->__toString(),
37
            $this->response->getStatusCode(),
38
            $this->response->getReasonPhrase(),
39
            $this->getRawHeaders($this->response->getHeaders()),
40
            $this->response->getBody()
41
        );
42
    }
43
44
    /**
45
     * @param array $headers
46
     * @return string
47
     */
48
    private function getRawHeaders(array $headers)
49
    {
50
        $rawHeaders = '';
51
        foreach ($headers as $key => $value) {
52
            $rawHeaders .= sprintf("%s: %s\n", $key, is_array($value) ? implode(", ", $value) : $value);
53
        }
54
        $rawHeaders .= "\n";
55
56
        return $rawHeaders;
57
    }
58
}
59