Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mahelbir committed Sep 8, 2022
0 parents commit 8bbb7a1
Show file tree
Hide file tree
Showing 5 changed files with 357 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.idea/
vendor/
test.php
composer.lock
21 changes: 21 additions & 0 deletions LISENCE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Mahmuthan Elbir

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
70 changes: 70 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Mclient

[![Latest version][ico-version]][link-packagist]
[![Software License][ico-license]][link-license]
[![Total Downloads][ico-downloads]][link-downloads]

Mclient is a simple async request wrapper for Guzzle.

## Requirements

PHP 7.1+

[Guzzle 7.0+](https://github.com/guzzle/guzzle)

## Installation

Simply add a dependency on `mahelbir/mclient` to your composer.json file if you
use [Composer](https://getcomposer.org/) to manage the dependencies of your project:

```sh
composer require mahelbir/mclient
```

Although it's recommended to use Composer, you can actually include files anyway you want.

## Usage

```php
$mclient = new \Mahelbir\Mclient();

//Library options
$mclient->setTimeout(10);
$mclient->setConnectTimeout(5);
$mclient->setConcurrency(100);

// Async multiple requests
$mclient->request('GET', 'http://httpbin.org/get', ['X-CUSTOM-HEADER' => 'Value'], ['proxy' => '127.0.0.1:8080'], 'request_1_extra_data');
$mclient->post('http://httpbin.org/post', ['data' => 'value'], ['User-Agent' => 'Googlebot'], [], 'request_2_extra_data');
$responses = $mclient->execute();
foreach ($responses as $response) {
$status = $response['code'];
$body = $response['body'];
$headers = $response['headers'];
$request = $response['request'];
$extra = $response['extra'];
}

// Send true parameter to send single request
$mclient->get('http://httpbin.org/get');
$response = $mclient->execute(true);

// All request options same with Guzzle except interface option
$mclient->get('http://google.com', [], [], ['interface' => '2001:db8:3333:4444:5555:6666:7777:8888']);
```

## License

The MIT License (MIT). Please see [License File](LISENCE) for more information.

[ico-version]: https://img.shields.io/packagist/v/mahelbir/mclient.svg?style=flat-square

[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square

[ico-downloads]: https://img.shields.io/packagist/dt/mahelbir/mclient.svg?style=flat-square&v=2

[link-packagist]: https://packagist.org/packages/mahelbir/mclient

[link-license]: LISENCE

[link-downloads]: https://packagist.org/packages/mahelbir/mclient
22 changes: 22 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "mahelbir/mclient",
"description": "Simple async request wrapper for Guzzle",
"type": "library",
"homepage": "https://github.com/mahelbir/mclient",
"license": "MIT",
"authors": [
{
"name": "Mahmuthan Elbir",
"email": "me@mahmuthanelbir.com.tr"
}
],
"autoload": {
"psr-4": {
"Mahelbir\\": "src/"
}
},
"require": {
"php": ">=7.1",
"guzzlehttp/guzzle": ">=7.0.0"
}
}
240 changes: 240 additions & 0 deletions src/Mclient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
<?php

/**
* Simple async request wrapper for Guzzle
*
* @author Mahmuthan Elbir <me@mahmuthanelbir.com.tr>
* @license MIT
*/

namespace Mahelbir;

use Exception;
use Generator;
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Exception\BadResponseException;

class Mclient
{
/**
* @var Client
*/
protected $client;
/**
* @var array
*/
protected $requests;
/**
* @var array
*/
protected $responses;
/**
* @var int
*/
protected $timeout;
/**
* @var int
*/
protected $connectTimeout;
/**
* @var int
*/
protected $concurrency;

/**
* @var string
*/
private $version = "1.0";

/**
*
*/
public function __construct($concurrency = 50, $connectTimeout = 5, $timeout = 0)
{
$this->client = new Client();
$this->setTimeout($timeout);
$this->setConnectTimeout($connectTimeout);
$this->setConcurrency($concurrency);
}

/**
* @param string $method
* @param string $url
* @param array $headers
* @param array $options
* @param null $extra
* @return void
*/
public function request(string $method, string $url, array $headers = [], array $options = [], $extra = null): void
{
$headers = array_change_key_case($headers);
$options = array_change_key_case($options);
if (!empty($options["interface"]) && empty($options["proxy"])) {
$options["curl"][CURLOPT_IPRESOLVE] = stristr($options["interface"], ":") ? CURL_IPRESOLVE_V6 : CURL_IPRESOLVE_V4;
$options["curl"][CURLOPT_INTERFACE] = $options["interface"];
}
$options["verify"] = false;
if (empty($headers["user-agent"]))
$headers["user-agent"] = 'Mclient/' . $this->version;

$this->requests[] = [
"method" => strtoupper($method),
"url" => $url,
"headers" => $headers,
"options" => $options,
"extra" => $extra
];
}

/**
* @param string $url
* @param array|string $data
* @param array $headers
* @param array $options
* @param null $extra
* @return void
*/
public function post(string $url, $data, array $headers = [], array $options = [], $extra = null): void
{
if (is_array($data)) {
$options["form_params"] = $data;
} else {
$options["body"] = $data;
}
$this->request("POST", $url, $headers, $options, $extra);
}

/**
* @param string $url
* @param array $data
* @param array $headers
* @param array $options
* @param null $extra
* @return void
*/
public function get(string $url, array $data = [], array $headers = [], array $options = [], $extra = null): void
{
if (!empty($data))
$options["query"] = $data;
$this->request("GET", $url, $headers, $options, $extra);
}

/**
* @param bool $single
* @return array
*/
public function execute(bool $single = false): array
{
$this->generateResponses();
return $single ? $this->responses[0] : $this->responses;
}

/**
* @return int
*/
public function getTimeout(): int
{
return $this->timeout;
}

/**
* @param int $timeout
*/
public function setTimeout(int $timeout): void
{
$this->timeout = $timeout;
}

/**
* @return int
*/
public function getConnectTimeout(): int
{
return $this->connectTimeout;
}

/**
* @param int $connectTimeout
*/
public function setConnectTimeout(int $connectTimeout): void
{
$this->connectTimeout = $connectTimeout;
}

/**
* @return int
*/
public function getConcurrency(): int
{
return $this->concurrency;
}

/**
* @param int $concurrency
*/
public function setConcurrency(int $concurrency): void
{
$this->concurrency = $concurrency;
}

/**
* @return void
*/
protected function generateResponses(): void
{
$this->responses = [];
$pool = new Pool($this->client, $this->generateRequests(), [
'concurrency' => $this->getConcurrency(),
'fulfilled' => function (Response $response, $request) {
$extra = $request["extra"];
unset($request["extra"]);
$this->responses[] = [
"code" => $response->getStatusCode(),
"body" => trim($response->getBody()->getContents()),
"headers" => array_change_key_case($response->getHeaders()),
"request" => $request,
"extra" => $extra
];
},
'rejected' => function (Exception $e, $request) {
$body = '';
$headers = [];
if ($e instanceof BadResponseException) {
$body = trim($e->getResponse()->getBody()->getContents());
$headers = array_change_key_case($e->getResponse()->getHeaders());
}
$extra = $request["extra"];
unset($request["extra"]);
$this->responses[] = [
"code" => $e->getCode(),
"body" => $body,
"headers" => $headers,
"request" => $request,
"extra" => $extra
];
},
]);
$pool->promise()->wait();
$this->requests = [];
}

/**
* @return Generator
*/
protected function generateRequests(): Generator
{
foreach ($this->requests ?? [] as $request) {
yield $request => function () use ($request) {
return $this->client->requestAsync($request["method"], $request["url"], array_merge($request["options"], [
"headers" => $request["headers"],
"timeout" => $this->getTimeout(),
"connect_timeout" => $this->getConnectTimeout(),
"http_errors" => false
]));
};
}
}

}

0 comments on commit 8bbb7a1

Please sign in to comment.