Completed
Pull Request — master (#50)
by Tobias
06:12
created

CurlCommandFormatter::formatRequest()   B

Complexity

Conditions 6
Paths 18

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 0
loc 26
rs 8.439
cc 6
eloc 16
nc 18
nop 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
    public function formatRequest(RequestInterface $request)
20
    {
21
        $command = sprintf('curl %s', escapeshellarg($request->getUri()));
22
        if ($request->getProtocolVersion() === '1.0') {
23
            $command .= ' --http1.0';
24
        } elseif ($request->getProtocolVersion() === '2.0') {
25
            $command .= ' --http2';
26
        }
27
28
        $command .= ' --request '.$request->getMethod();
29
30
        foreach ($request->getHeaders() as $name => $values) {
31
            $command .= sprintf(' -H %s', escapeshellarg($name.': '.$request->getHeaderLine($name)));
32
        }
33
34
        $body = $request->getBody();
35
        if ($body->getSize() > 0) {
36
            if (!$body->isSeekable()) {
37
                throw new \RuntimeException('Cannot take data from a stream that is not seekable');
38
            }
39
            $command .= sprintf(' --data %s', escapeshellarg($body->__toString()));
40
            $body->rewind();
41
        }
42
43
        return $command;
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function formatResponse(ResponseInterface $response)
50
    {
51
        return '';
52
    }
53
}
54