Completed
Pull Request — master (#94)
by
unknown
11:48 queued 05:29
created

CurlCommandFormatter::formatRequest()   D

Complexity

Conditions 9
Paths 63

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 9.0894

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 38
ccs 26
cts 29
cp 0.8966
rs 4.909
cc 9
eloc 25
nc 63
nop 1
crap 9.0894
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 5
    public function formatRequest(RequestInterface $request)
20
    {
21 5
        $command = sprintf('curl %s', escapeshellarg((string) $request->getUri()->withFragment('')));
22 5
        if ('1.0' === $request->getProtocolVersion()) {
23
            $command .= ' --http1.0';
24 5
        } elseif ('2.0' === $request->getProtocolVersion()) {
25 1
            $command .= ' --http2';
26 1
        }
27
28 5
        $method = strtoupper($request->getMethod());
29 5
        if ('HEAD' === $method) {
30
            $command .= ' --head';
31 5
        } elseif ('GET' !== $method) {
32 3
            $command .= ' --request '.$method;
33 3
        }
34
35 5
        $command .= $this->getHeadersAsCommandOptions($request);
36
37 5
        $body = $request->getBody();
38 5
        if ($body->getSize() > 0) {
39 3
            if ($body->isSeekable()) {
40 2
                $data = $body->__toString();
41 2
                $body->rewind();
42 2
                if (preg_match('/[\x00-\x1F\x7F]/', $data)) {
43 1
                    $data = '[binary stream omitted]';
44 1
                }
45 2
            } else {
46 1
                $data = '[non-seekable stream omitted]';
47
            }
48
49 3
            $escapedData = @escapeshellarg($data) or
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
50
                die("We couldn't not escape the data properly: error was '$php_errormsg'");
0 ignored issues
show
Coding Style Compatibility introduced by
The method formatRequest() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
51
52 3
            $command .= sprintf(' --data %s', $escapedData);
53 3
        }
54
55 5
        return $command;
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61 1
    public function formatResponse(ResponseInterface $response)
62
    {
63 1
        return '';
64
    }
65
66
    /**
67
     * @param RequestInterface $request
68
     *
69
     * @return string
70
     */
71 5
    private function getHeadersAsCommandOptions(RequestInterface $request)
72
    {
73 5
        $command = '';
74 5
        foreach ($request->getHeaders() as $name => $values) {
75 2
            if ('host' === strtolower($name) && $values[0] === $request->getUri()->getHost()) {
76
                continue;
77
            }
78
79 2
            if ('user-agent' === strtolower($name)) {
80 1
                $command .= sprintf(' -A %s', escapeshellarg($values[0]));
81
82 1
                continue;
83
            }
84
85 1
            $command .= sprintf(' -H %s', escapeshellarg($name.': '.$request->getHeaderLine($name)));
86 5
        }
87
88 5
        return $command;
89
    }
90
}
91