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

CurlCommandFormatter   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 5
Bugs 2 Features 1
Metric Value
wmc 13
c 5
b 2
f 1
lcom 0
cbo 3
dl 0
loc 67
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
C formatRequest() 0 29 7
A formatResponse() 0 4 1
B getHeadersAsCommandOptions() 0 18 5
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((string) $request->getUri()->withFragment('')));
22
        if ($request->getProtocolVersion() === '1.0') {
23
            $command .= ' --http1.0';
24
        } elseif ($request->getProtocolVersion() === '2.0') {
25
            $command .= ' --http2';
26
        }
27
28
        $method = strtoupper($request->getMethod());
29
        if ('HEAD' === $method) {
30
            $command .= ' --head';
31
        } elseif ('GET' !== $method) {
32
            $command .= ' --request '.$method;
33
        }
34
35
        $command .= $this->getHeadersAsCommandOptions($request);
36
37
        $body = $request->getBody();
38
        if ($body->getSize() > 0) {
39
            if (!$body->isSeekable()) {
40
                return 'Cant format Request as cUrl command if body stream is not seekable.';
41
            }
42
            $command .= sprintf(' --data %s', escapeshellarg($body->__toString()));
43
            $body->rewind();
44
        }
45
46
        return $command;
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function formatResponse(ResponseInterface $response)
53
    {
54
        return '';
55
    }
56
57
    /**
58
     * @param RequestInterface $request
59
     *
60
     * @return string
61
     */
62
    private function getHeadersAsCommandOptions(RequestInterface $request)
63
    {
64
        $command = '';
65
        foreach ($request->getHeaders() as $name => $values) {
66
            if ('host' === strtolower($name) && $values[0] === $request->getUri()->getHost()) {
67
                continue;
68
            }
69
70
            if ('user-agent' === strtolower($name)) {
71
                $command .= sprintf('-A %s', escapeshellarg($values[0]));
72
                continue;
73
            }
74
75
            $command .= sprintf(' -H %s', escapeshellarg($name.': '.$request->getHeaderLine($name)));
76
        }
77
78
        return $command;
79
    }
80
}
81