Open Monograph Press  3.3.0
CurlCommandFormatter.php
1 <?php
2 
4 
8 
15 {
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  // escapeshellarg argument max length on Windows, but longer body in curl command would be impractical anyways
40  if ($body->getSize() > 8192) {
41  $data = '[too long stream omitted]';
42  } elseif ($body->isSeekable()) {
43  $data = $body->__toString();
44  $body->rewind();
45  if (preg_match('/[\x00-\x1F\x7F]/', $data)) {
46  $data = '[binary stream omitted]';
47  }
48  } else {
49  $data = '[non-seekable stream omitted]';
50  }
51  $escapedData = @escapeshellarg($data);
52  if (empty($escapedData)) {
53  $escapedData = 'We couldn\'t not escape the data properly';
54  }
55 
56  $command .= sprintf(' --data %s', $escapedData);
57  }
58 
59  return $command;
60  }
61 
65  public function formatResponse(ResponseInterface $response)
66  {
67  return '';
68  }
69 
75  private function getHeadersAsCommandOptions(RequestInterface $request)
76  {
77  $command = '';
78  foreach ($request->getHeaders() as $name => $values) {
79  if ('host' === strtolower($name) && $values[0] === $request->getUri()->getHost()) {
80  continue;
81  }
82 
83  if ('user-agent' === strtolower($name)) {
84  $command .= sprintf(' -A %s', escapeshellarg($values[0]));
85 
86  continue;
87  }
88 
89  $command .= sprintf(' -H %s', escapeshellarg($name.': '.$request->getHeaderLine($name)));
90  }
91 
92  return $command;
93  }
94 }
Psr\Http\Message\RequestInterface
Definition: vendor/psr/http-message/src/RequestInterface.php:24
Http\Message\Formatter\CurlCommandFormatter
Definition: CurlCommandFormatter.php:14
Http\Message\Formatter\CurlCommandFormatter\formatRequest
formatRequest(RequestInterface $request)
Definition: CurlCommandFormatter.php:19
Http\Message\Formatter
Definition: CurlCommandFormatter.php:3
Psr\Http\Message\ResponseInterface
Definition: vendor/psr/http-message/src/ResponseInterface.php:20
Http\Message\Formatter\CurlCommandFormatter\formatResponse
formatResponse(ResponseInterface $response)
Definition: CurlCommandFormatter.php:65
Http\Message\Formatter
Definition: Formatter.php:13