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