From 3d74aeae7588e5f7a4d51808e9e1a91867920fc9 Mon Sep 17 00:00:00 2001 From: Dmitriy Zhavoronkov Date: Sat, 12 Sep 2020 01:53:21 +0300 Subject: [PATCH] repo init --- .gitignore | 3 ++ README.md | 27 +++++++++++++++ src/CurlToGuzzle.php | 62 +++++++++++++++++++++++++++++++++++ src/CurlToGuzzleException.php | 7 ++++ 4 files changed, 99 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 src/CurlToGuzzle.php create mode 100644 src/CurlToGuzzleException.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ed7a7d2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/.idea +/composer.* +/vendor diff --git a/README.md b/README.md new file mode 100644 index 0000000..f1f2bff --- /dev/null +++ b/README.md @@ -0,0 +1,27 @@ +# cURL to Guzzle converter + +Simple script that helps you to convert cURL query string to Guzzle config array. + +Very alpha version. + +## Usage example + +Sample input + +``` +curl 'https://www.example.com/api/endpoint' \ + -H 'accept: application/json' \ + ... +``` + +Usage + +``` +$c2g = new \DimazzzZ\CurlToGuzzle($str); + +$config = $c2g->getConfig(); + +$client = new \GuzzleHttp\Client($config); + +$response = $client->get('')->getBody()->getContents(); +``` diff --git a/src/CurlToGuzzle.php b/src/CurlToGuzzle.php new file mode 100644 index 0000000..7ecc85d --- /dev/null +++ b/src/CurlToGuzzle.php @@ -0,0 +1,62 @@ +curlString = $str; + $this->parseOptionsAndValues(); + + $this->setBaseUri(); + $this->setHeaders(); + } + + public function parseOptionsAndValues() + { + preg_match_all("~ --?[A-Za-z]+( '[^']+')?~", $this->curlString, $opts); + + $this->optionValuePairs = array_map(function ($item) { + [$option, $value] = explode(' ', trim($item), 2); + $value = trim($value, '\'\"'); + + return [$option, $value]; + }, $opts[0]); + } + + public function setBaseUri() + { + preg_match("~^curl '.+'~", $this->curlString, $match); + [, $value] = explode(' ', $match[0], 2); + + $value = trim($value, '\'\"'); + + $pu = parse_url($value); + + if (!in_array($pu['scheme'], ['http', 'https'])) { + throw new CurlToGuzzleException('Unsupported protocol (scheme): ' . $pu['scheme']); + } + + $this->guzzleConfig['base_uri'] = $value; + } + + public function setHeaders() + { + foreach ($this->optionValuePairs as $key => $value) { + if ($value[0] == '-H') { + [$name, $value] = explode(': ', $value[1], 2); + $this->guzzleConfig['headers'][$name] = $value; + } + } + } + + public function getConfig() + { + return $this->guzzleConfig; + } +} diff --git a/src/CurlToGuzzleException.php b/src/CurlToGuzzleException.php new file mode 100644 index 0000000..222a04c --- /dev/null +++ b/src/CurlToGuzzleException.php @@ -0,0 +1,7 @@ +