Completed
Push — master ( 2edd63...4b777b )
by Tobias
06:07 queued 04:08
created

CurlCommandFormatter::formatResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 4
c 1
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Http\Message\Formatter;
4
5
use Http\Message\Formatter;
6
use Psr\Http\Message\RequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
9
/**
10
 * A formatter that prints a cURL command for HTTP requests.
11
 *
12
 * @author Tobias Nyholm <[email protected]>
13
 */
14
class CurlCommandFormatter implements Formatter
15
{
16
    /**
17
     * {@inheritdoc}
18
     */
19 3
    public function formatRequest(RequestInterface $request)
20
    {
21 3
        $command = sprintf('curl %s', escapeshellarg((string) $request->getUri()->withFragment('')));
22 3
        if ($request->getProtocolVersion() === '1.0') {
23
            $command .= ' --http1.0';
24 3
        } elseif ($request->getProtocolVersion() === '2.0') {
25 1
            $command .= ' --http2';
26 1
        }
27
28 3
        $method = strtoupper($request->getMethod());
29 3
        if ('HEAD' === $method) {
30
            $command .= ' --head';
31 3
        } elseif ('GET' !== $method) {
32 1
            $command .= ' --request '.$method;
33 1
        }
34
35 3
        $command .= $this->getHeadersAsCommandOptions($request);
36
37 3
        $body = $request->getBody();
38 3
        if ($body->getSize() > 0) {
39 1
            if (!$body->isSeekable()) {
40
                return 'Cant format Request as cUrl command if body stream is not seekable.';
41
            }
42 1
            $command .= sprintf(' --data %s', escapeshellarg($body->__toString()));
43 1
            $body->rewind();
44 1
        }
45
46 3
        return $command;
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52 1
    public function formatResponse(ResponseInterface $response)
53
    {
54 1
        return '';
55
    }
56
57
    /**
58
     * @param RequestInterface $request
59
     *
60
     * @return string
61
     */
62 3
    private function getHeadersAsCommandOptions(RequestInterface $request)
63
    {
64 3
        $command = '';
65 3
        foreach ($request->getHeaders() as $name => $values) {
66 2
            if ('host' === strtolower($name) && $values[0] === $request->getUri()->getHost()) {
67
                continue;
68
            }
69
70 2
            if ('user-agent' === strtolower($name)) {
71 1
                $command .= sprintf(' -A %s', escapeshellarg($values[0]));
72 1
                continue;
73
            }
74
75 1
            $command .= sprintf(' -H %s', escapeshellarg($name.': '.$request->getHeaderLine($name)));
76 3
        }
77
78 3
        return $command;
79
    }
80
}
81