Skip to content

Commit

Permalink
repo init
Browse files Browse the repository at this point in the history
  • Loading branch information
DimazzzZ committed Sep 11, 2020
0 parents commit 3d74aea
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/.idea
/composer.*
/vendor
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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();
```
62 changes: 62 additions & 0 deletions src/CurlToGuzzle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace DimazzzZ;

class CurlToGuzzle
{
private string $curlString;
private array $optionValuePairs = [];
private array $guzzleConfig = [];

public function __construct(string $str)
{
$this->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;
}
}
7 changes: 7 additions & 0 deletions src/CurlToGuzzleException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace DimazzzZ;

class CurlToGuzzleException extends \Exception
{
}

0 comments on commit 3d74aea

Please sign in to comment.