CurlCommandFormatter.php
6 months ago
FullHttpMessageFormatter.php
6 months ago
SimpleFormatter.php
6 months ago
CurlCommandFormatter.php
92 lines
| 1 | <?php |
| 2 | |
| 3 | namespace AmeliaHttp\Message\Formatter; |
| 4 | |
| 5 | use AmeliaHttp\Message\Formatter; |
| 6 | use AmeliaVendor\Psr\Http\Message\RequestInterface; |
| 7 | use AmeliaVendor\Psr\Http\Message\ResponseInterface; |
| 8 | |
| 9 | /** |
| 10 | * A formatter that prints a cURL command for HTTP requests. |
| 11 | * |
| 12 | * @author Tobias Nyholm <tobias.nyholm@gmail.com> |
| 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 ('1.0' === $request->getProtocolVersion()) { |
| 23 | $command .= ' --http1.0'; |
| 24 | } elseif ('2.0' === $request->getProtocolVersion()) { |
| 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 | $data = $body->__toString(); |
| 41 | $body->rewind(); |
| 42 | if (preg_match('/[\x00-\x1F\x7F]/', $data)) { |
| 43 | $data = '[binary stream omitted]'; |
| 44 | } |
| 45 | } else { |
| 46 | $data = '[non-seekable stream omitted]'; |
| 47 | } |
| 48 | $escapedData = @escapeshellarg($data); |
| 49 | if (empty($escapedData)) { |
| 50 | $escapedData = 'We couldn\'t not escape the data properly'; |
| 51 | } |
| 52 | |
| 53 | $command .= sprintf(' --data %s', $escapedData); |
| 54 | } |
| 55 | |
| 56 | return $command; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * {@inheritdoc} |
| 61 | */ |
| 62 | public function formatResponse(ResponseInterface $response) |
| 63 | { |
| 64 | return ''; |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * @param RequestInterface $request |
| 69 | * |
| 70 | * @return string |
| 71 | */ |
| 72 | private function getHeadersAsCommandOptions(RequestInterface $request) |
| 73 | { |
| 74 | $command = ''; |
| 75 | foreach ($request->getHeaders() as $name => $values) { |
| 76 | if ('host' === strtolower($name) && $values[0] === $request->getUri()->getHost()) { |
| 77 | continue; |
| 78 | } |
| 79 | |
| 80 | if ('user-agent' === strtolower($name)) { |
| 81 | $command .= sprintf(' -A %s', escapeshellarg($values[0])); |
| 82 | |
| 83 | continue; |
| 84 | } |
| 85 | |
| 86 | $command .= sprintf(' -H %s', escapeshellarg($name.': '.$request->getHeaderLine($name))); |
| 87 | } |
| 88 | |
| 89 | return $command; |
| 90 | } |
| 91 | } |
| 92 |