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
|
2 |
|
public function formatRequest(RequestInterface $request) |
20
|
|
|
{ |
21
|
2 |
|
$command = sprintf('curl %s', escapeshellarg((string) $request->getUri()->withFragment(''))); |
22
|
2 |
|
if ($request->getProtocolVersion() === '1.0') { |
23
|
|
|
$command .= ' --http1.0'; |
24
|
2 |
|
} elseif ($request->getProtocolVersion() === '2.0') { |
25
|
1 |
|
$command .= ' --http2'; |
26
|
1 |
|
} |
27
|
|
|
|
28
|
2 |
|
$method = strtoupper($request->getMethod()); |
29
|
2 |
|
if ('HEAD' === $method) { |
30
|
|
|
$command .= ' --head'; |
31
|
2 |
|
} elseif ('GET' !== $method) { |
32
|
1 |
|
$command .= ' --request '.$method; |
33
|
1 |
|
} |
34
|
|
|
|
35
|
2 |
|
$command .= $this->getHeadersAsCommandOptions($request); |
36
|
|
|
|
37
|
2 |
|
$body = $request->getBody(); |
38
|
2 |
|
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
|
2 |
|
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
|
2 |
|
private function getHeadersAsCommandOptions(RequestInterface $request) |
63
|
|
|
{ |
64
|
2 |
|
$command = ''; |
65
|
2 |
|
foreach ($request->getHeaders() as $name => $values) { |
66
|
1 |
|
if ('host' === strtolower($name) && $values[0] === $request->getUri()->getHost()) { |
67
|
|
|
continue; |
68
|
|
|
} |
69
|
|
|
|
70
|
1 |
|
if ('user-agent' === strtolower($name)) { |
71
|
|
|
$command .= sprintf('-A %s', escapeshellarg($values[0])); |
72
|
|
|
continue; |
73
|
|
|
} |
74
|
|
|
|
75
|
1 |
|
$command .= sprintf(' -H %s', escapeshellarg($name.': '.$request->getHeaderLine($name))); |
76
|
2 |
|
} |
77
|
|
|
|
78
|
2 |
|
return $command; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|