ReactPHP HttpClient Adapter for Guzzle6, for Guzzle5 check ReactGuzzleRing

Overview

react-guzzle-psr7

Build Status Latest Stable Version Total Downloads Coverage Status License

ReactPHP HttpClient Adapter for Guzzle6, for Guzzle5 check ReactGuzzleRing

Installation

To install via Composer, use the command below, it will automatically detect the latest version and bind it with ~.

composer require wyrihaximus/react-guzzle-psr7 

Examples

Asynchronous



require 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';

$loop = \React\EventLoop\Factory::create();
$handler = new \WyriHaximus\React\GuzzlePsr7\HttpClientAdapter($loop);

$client = new \GuzzleHttp\Client([
    'handler' => \GuzzleHttp\HandlerStack::create($handler),
]);

$client->getAsync('http://github.com/')->then(function ($response) {
    var_export($response);
    var_export((string) $response->getBody());
});

$client->getAsync('http://php.net/')->then(function ($response) {
    var_export($response);
    var_export((string) $response->getBody());
});

$loop->run();

Synchronous



require 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';

$loop = \React\EventLoop\Factory::create();
$handler = new \WyriHaximus\React\GuzzlePsr7\HttpClientAdapter($loop);

$client = new \GuzzleHttp\Client([
    'handler' => \GuzzleHttp\HandlerStack::create($handler),
]);

var_export((string) $client->get('http://github.com/')->getBody());

See the examples directory for more ways to use this handler.

Contributing

Please see CONTRIBUTING for details.

License

Copyright 2015 Cees-Jan Kiewiet

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.

Comments
  • Doesnt work with PHP7 and ExtEventLoop

    Doesnt work with PHP7 and ExtEventLoop

    Hi,

    I have php 7 installed and I tried only working extension "event.so" for ReactPHP on PHP 7, but it doesnt work at all, it just make php to take 99% cpu power and 'freeze'

    Testing code

    <?php
    require __DIR__.'/../vendor/autoload.php';
    
    
    $loop = \React\EventLoop\Factory::create();
    $handler = new \WyriHaximus\React\GuzzlePsr7\HttpClientAdapter($loop);
    
    $client = new \GuzzleHttp\Client([
        'base_uri' => 'http://127.0.0.1/fake_web/',
        'handler' => \GuzzleHttp\HandlerStack::create($handler),
    ]);
    
    $response = $client->get('http://127.0.0.1/fake_web/'); # ! this is row that stops script !
    $html = (string) $response->getBody();
    

    When I try same code with StreamSelectLoop it works

    opened by reflexator 9
  • Stream doesn't work

    Stream doesn't work

    React Http client works with https://developer.gitter.im/docs/streaming-api:

    $loop = React\EventLoop\Factory::create();
    $react = (new React\HttpClient\Factory())->create($loop, (new React\Dns\Resolver\Factory())->createCached('8.8.8.8', $loop))
    
    $stream = $react->request('GET', 'https://stream.gitter.im/v1/rooms/'.$room.'/chatMessages', $headers);
    
    $stream->on('response', function ($response) {
        $response->on('data', function ($data) {
            var_dump($data);
        });
    });
    $stream->end();
    
    $loop->run();
    

    This library doesn't work (success function in then not run at all):

    $loop = React\EventLoop\Factory::create();
    
    $stack = GuzzleHttp\HandlerStack::create(new WyriHaximus\React\GuzzlePsr7\HttpClientAdapter($loop));
    $client = new GuzzleHttp\Client([
        'headers' => $headers,
        'handler' => $stack,
    ]);
    
    $stream = $client->getAsync('https://stream.gitter.im/v1/rooms/'.$room.'/chatMessages', ['stream' => true]);
    
    $stream->then(function ($response) {
        $body = $response->getBody();
        $data = '';
        while (!$body->eof()) {
            $data .= $body->read(1024);
        }
        var_dump($data);
    });
    
    $loop->run();
    
    opened by hason 9
  • Package is incompatible with react/http

    Package is incompatible with react/http

    {
        "name": "mdrost/react-guzzle-test",
        "require": {
            "react/http": "^0.6.0",
            "wyrihaximus/react-guzzle-psr7": "^2.0"
        }
    }
    

    outputs

    Your requirements could not be resolved to an installable set of packages.
    
      Problem 1
        - Installation request for react/http ^0.6.0 -> satisfiable by react/http[v0.6.0].
        - Installation request for wyrihaximus/react-guzzle-psr7 ^2.0 -> satisfiable by wyrihaximus/react-guzzle-psr7[2.0.0].
        - wyrihaximus/react-guzzle-http-client 4.0.0 requires clue/socks-react ^0.4.0 -> satisfiable by clue/socks-react[v0.4.0].
        - wyrihaximus/react-guzzle-psr7 2.0.0 requires wyrihaximus/react-guzzle-http-client ^4.0 -> satisfiable by wyrihaximus/react-guzzle-http-client[4.0.0].
        - clue/socks-react v0.4.0 requires react/socket 0.3.*|0.4.* -> satisfiable by react/socket[v0.3.0, v0.3.1, v0.3.2, v0.3.3, v0.3.4, v0.4.0, v0.4.1, v0.4.2, v0.4.3, v0.4.4, v0.4.5, v0.4.6].
        - Can only install one of: react/socket[v0.5.0, v0.3.0].
        - Can only install one of: react/socket[v0.5.0, v0.3.1].
        - Can only install one of: react/socket[v0.5.0, v0.3.2].
        - Can only install one of: react/socket[v0.5.0, v0.3.3].
        - Can only install one of: react/socket[v0.5.0, v0.3.4].
        - Can only install one of: react/socket[v0.5.0, v0.4.0].
        - Can only install one of: react/socket[v0.5.0, v0.4.1].
        - Can only install one of: react/socket[v0.5.0, v0.4.2].
        - Can only install one of: react/socket[v0.5.0, v0.4.3].
        - Can only install one of: react/socket[v0.5.0, v0.4.4].
        - Can only install one of: react/socket[v0.5.0, v0.4.5].
        - Can only install one of: react/socket[v0.5.0, v0.4.6].
        - react/http v0.6.0 requires react/socket ^0.5 -> satisfiable by react/socket[v0.5.0, v0.5.1].
        - Conclusion: don't install react/socket v0.5.1
    
    
    opened by mdrost 8
  • HTTPS Connection halts when the request is too large

    HTTPS Connection halts when the request is too large

    When sending a large file via multipart/form-data using HTTPS the connection stalls. I am able to reproduce this consistently with php 5.6 and PHP 7 (albeit both have a different limit).

    This may or may not be a problem in the underlying reactphp/socket-client or PHP ssl streams.

    And here an example to test:

    
    <?php
    
    require_once 'vendor/autoload.php';
    
    use \WyriHaximus\React as ReactHttp;
    use React\EventLoop\Factory as LoopFactory;
    
    
    $loop = LoopFactory::create();
    $handler = new ReactHttp\GuzzlePsr7\HttpClientAdapter($loop);
    $client = new GuzzleHttp\Client([
        'handler'   => \GuzzleHttp\HandlerStack::create($handler)
    ]);
    
    // PHP 5.6 works for me until the last number is 86.
    // PHP 7.x works for me until the last number is 88
    $AS = str_repeat("A", 28462 + 90);
    print "MD5SUM = ".md5($AS)."\n";
    
    $client->requestAsync(
        "POST", 
        "https://skizzordz.exis.cl/test-upload.php",
        [
            'multipart' => [
                [   
                    "name" => "file", 
                    "contents" => $AS,
                    "filename" => "A.txt"
                ]
            ]
        ])
        ->then(function($response) {
            print "RESPONSE = ".$response->getStatusCode()."\n";
            print "BODY = ".$response->getBody()."\n";
            die();
        })
        ->otherwise(function(Exception $error) {
            print("ERROR: " . $error->getMessage(). "\n");
            die();
        });
    
    while(1) $loop->run();
    
    opened by pwhelan 8
  • Promises not resolving when in a Periodic Timer

    Promises not resolving when in a Periodic Timer

    Hi, I'm not sure if its possible but I'm trying to poll an API every x seconds. But when I try the following for example the promises never get resolved. Am I doing something wrong?

    <?php
    require dirname(__DIR__) . '/vendor/autoload.php';
    
    use GuzzleHttp\Client;
    use GuzzleHttp\HandlerStack;
    use GuzzleHttp\Psr7\Response;
    use React\EventLoop\Factory;
    use WyriHaximus\React\GuzzlePsr7\HttpClientAdapter;
    
    $loop = Factory::create();
    
    $client = new Client([
        'handler' => HandlerStack::create(new HttpClientAdapter($loop)),
    ]);
    
    $loop->addPeriodicTimer(5, function() use (&$client) {
        echo 'Loading content', PHP_EOL;
    
        $promise = $client->getAsync('http://blog.wyrihaximus.net/');
        $promise->then(function(Response $response) { // Success callback
            var_dump($response);
            echo 'Content loaded', PHP_EOL;
        });
    });
    
    
    $loop->run();
    

    My actual use case is within the Amazon EC2 SDK to check if an instance has booted or not.

    opened by adamlc 8
  • What's the difference / which is better?

    What's the difference / which is better?

    I'm in the process of rewriting a library that depends on this repo. Today I came across this article which precisely details one way to make guzzle and react play nicely together – however I noticed some differences between your code and his.

    Did you base the current structure of your lib on the code in that article? If so, I would assume any differences must be due to your vision for improving on the article's code. If your lib is better, can you point out why?

    opened by garrettw 7
  • Possible incompatibility issue

    Possible incompatibility issue

    I'm using the ratchephpt/Pawl WS client on the same loop as the one I've set for this Guzzle handler.

    Async requests are generally fine but sync. requests either run instantly and work fine or they hang for a long while and then cause the WebSocket connection to die (Sending or Receiving messages fail without any exceptions).

    Using the default Guzzle handler along with Pawl works fine, but I do need async requests so am a bit stuck here.

    (Also would it be better if I posted this in reactphp/http-client since it uses that?)

    opened by Akhawais 6
  • Asynchronous request to cloud watch logs  AWS PHP

    Asynchronous request to cloud watch logs AWS PHP

    I am writing a function to log input to cloud watch logs. I want it as fast as possible. Normally I use synchronous request, e.g putLogEvents, currently the time difference is about 40ms. My question is how to speed up my putLogEvents or using putLogEventsAsync instead.

    Here is my code

    public function writeToCloudWatch($line)
       {
            $microTime = $this->timeProvider->getMicroTime();
    
            if (!isset($this->nextSequenceToken)){
                $responseModel = $this->client->describeLogStreams([
                    'logGroupName' => $this->logGroup,
                    'logStreamNamePrefix' => $this->logStream,
                ]);
                $this->nextSequenceToken = $responseModel['logStreams']['0']['uploadSequenceToken'];
            }
            try {
                $responseModel = $this->client->putLogEvents([
                    'logGroupName' => $this->logGroup,
                    'logStreamName' => $this->logStream,
                    'logEvents' => [
                        [
                            'message' => $line,
                            'timestamp' => $microTime,
                        ]
                    ],
                    'sequenceToken' => $this->nextSequenceToken
                ]);
                if (isset($responseModel['nextSequenceToken'])) {
                    $this->nextSequenceToken = $responseModel['nextSequenceToken'];
                }
            } catch (CloudWatchLogsException $e) {
                // We don't want any exception when putLogEvents is not working
            }
        }
    
    opened by lastday154 5
  • Can't shift from an empty datastructure

    Can't shift from an empty datastructure

    Hello! I've used your tool for making async requests to AWS S3 buckets. But i got an error:

    In FutureTickQueue.php line 46:                                           
    Can't shift from an empty datastructure 
    

    It is weird because i don't need ticking manually event loop or calling wait as far as i use custom HTTP handler.

            $loop = EventLoopFactory::create();
            $handler = new \WyriHaximus\React\GuzzlePsr7\HttpClientAdapter($loop);
    
            $s3Client = new S3Client([
                'http_handler' => \GuzzleHttp\HandlerStack::create($handler),
                'version' => 'latest',
                'region' => getenv('AWS_REGION'),
                'validate' => false
            ]);
    
            $dir1 = dirname(dirname(__DIR__)) . "/data/temp-test-medium-1";
            mkdir($dir1);
            $s3Client->downloadBucketAsync($dir1, 'test-medium-1')->then(function(){
                echo "Done 1\n";
            });
    
            $dir2 = dirname(dirname(__DIR__)) . "/data/temp-test-medium-2";
            mkdir($dir2);
            $s3Client->downloadBucketAsync($dir2, 'test-medium-2')->then(function(){
                echo "Done 2\n";
            });
    
            $loop->run();
            echo "finished\n";
    

    Thanks in advance!

    opened by yuklia 4
  • asynchronous requests not working

    asynchronous requests not working

    Hi,

    I tried with loop example: with send mail, this process like sync as not sent mail in behind.

    $loop = \React\EventLoop\Factory::create(); $handler = new \WyriHaximus\React\GuzzlePsr7\HttpClientAdapter($loop);

    $client = new \GuzzleHttp\Client([ 'handler' => \GuzzleHttp\HandlerStack::create($handler), ]);

    $client->getAsync('http://github.com/')->then(function ($response) { var_export($response); var_export((string) $response->getBody()); });

    $client->getAsync('http://php.net/')->then(function ($response) { var_export($response); var_export((string) $response->getBody()); });

    $loop->run();

    opened by akwatra 4
  • Multiple Request

    Multiple Request

    helo how to get result without waiting all request. example :

    $loop = \React\EventLoop\Factory::create();
            $handler = new \WyriHaximus\React\GuzzlePsr7\HttpClientAdapter($loop);
    
            $client = new \GuzzleHttp\Client([
                'handler' => \GuzzleHttp\HandlerStack::create($handler),
            ]);
    
            $client->getAsync('http://Example4.com')->then(function ($response) {
                var_export($response);
            });
    
            $client->getAsync('http://Example1.com')->then(function ($response) {
                var_export($response);
            });
    
            $client->getAsync('http://Example2.com')->then(function ($response) {
                var_export($response);
            });
    
            $client->getAsync('http://Example3.com')->then(function ($response) {
                var_export($response);
    
            });
    
            $loop->run();
    

    how to get result 'http://Example1.com' when sucess without waitting all;

    thanks

    opened by richardus1992 4
Releases(2.1.3)
Owner
Cees-Jan Kiewiet
@WyriMaps, @reactphp core maintainer, highly interested in asynchronous programming, and generic maniac
Cees-Jan Kiewiet
A PHP HttpClient for the Neo4j ReST API with MultiDB Support

NeoClient This repository has moved Neoxygen's NeoClient has been moved to https://github.com/graphaware/neo4j-php-client Version 3 of this library is

Neoxygen 120 Oct 19, 2022
Spike is a fast reverse proxy built on top of ReactPHP that helps to expose your local services to the internet.

Spike is a fast reverse proxy built on top of ReactPHP that helps to expose your local services to the internet. 简体中文 Installation Install via compose

Tao 649 Dec 26, 2022
Event-driven, streaming HTTP client and server implementation for ReactPHP

HTTP Event-driven, streaming HTTP client and server implementation for ReactPHP. This HTTP library provides re-usable implementations for an HTTP clie

ReactPHP 640 Dec 29, 2022
Opsie Operator is a CLI to check your website for HTTP downtime.

Opsie Operator Monitor any website. Run in Docker or any Kubernetes cluster. Send webhooks. ?? Supporting If you are using one or more Renoki Co. open

opsie 14 Dec 6, 2021
The HttpClient component provides powerful methods to fetch HTTP resources synchronously or asynchronously.

HttpClient component The HttpClient component provides powerful methods to fetch HTTP resources synchronously or asynchronously. Resources Documentati

Symfony 1.7k Jan 6, 2023
A PHP HttpClient for the Neo4j ReST API with MultiDB Support

NeoClient This repository has moved Neoxygen's NeoClient has been moved to https://github.com/graphaware/neo4j-php-client Version 3 of this library is

Neoxygen 120 Oct 19, 2022
This tool check syntax of PHP files faster than serial check with fancier output.

PHP Parallel Lint This application checks syntax of PHP files in parallel. It can output in plain text, colored text, json and checksyntax formats. Ad

PHP Parallel lint 202 Dec 22, 2022
CRUD php application to check in and check out employees and show daily building occupation

CRUD php application to check in and check out employees and show daily building occupation. Employees are required to self check their temperature and tick a checkbox to specify whether their temperature is below 38°C else they are invited to stay home. (Implemented in php with bootstrap4 for styling and datatable jquery plugin for table formatting and additional features).

null 2 Feb 20, 2022
PHP Parallel Lint - This tool check syntax of PHP files faster than serial check with fancier output

PHP Parallel Lint This application checks syntax of PHP files in parallel. It can output in plain text, colored text, json and checksyntax formats. Ad

PHP Parallel lint 156 Apr 24, 2022
ReactPHP Shell, based on the Symfony Console component.

Pecan Event-driven, non-blocking shell for ReactPHP. Pecan (/pɪˈkɑːn/) provides a non-blocking alternative to the shell provided in the Symfony Consol

Michael Crumm 43 Sep 4, 2022
PHPUnit assertions for testing ReactPHP promises

ReactPHP Promises Testing A library that provides a set of convenient assertions for testing ReactPHP promises. Under the hood uses clue/php-block-rea

Sergey Zhuk 30 Dec 8, 2022
Performant pure-PHP AMQP (RabbitMQ) sync/async (ReactPHP) library

BunnyPHP Performant pure-PHP AMQP (RabbitMQ) sync/async (ReactPHP) library Requirements BunnyPHP requires PHP 7.1 and newer. Installation Add as Compo

Jakub Kulhan 641 Dec 29, 2022
Cronlike scheduler running inside a ReactPHP Event Loop

Cronlike scheduler running inside a ReactPHP Event Loop Install To install via Composer, use the command below, it will automatically detect the lates

Cees-Jan Kiewiet 35 Jul 12, 2022
Spike is a fast reverse proxy built on top of ReactPHP that helps to expose your local services to the internet.

Spike is a fast reverse proxy built on top of ReactPHP that helps to expose your local services to the internet. 简体中文 Installation Install via compose

Tao 649 Dec 26, 2022
Async Redis client implementation, built on top of ReactPHP.

clue/reactphp-redis Async Redis client implementation, built on top of ReactPHP. Redis is an open source, advanced, in-memory key-value database. It o

Christian Lück 240 Dec 20, 2022
This library brought ReactPHP and QueryList together

ReactPHP QueryList This library brought ReactPHP and QueryList together. Installation composer require ahmard/reactphp-querylist Usage Playing with Q

Ahmad Mustapha 5 Nov 19, 2021
Simple and universal connection pool for ReactPHP applications.

szado/reactphp-connection-pool Async and flexible pool for any type of connections built on top of ReactPHP. Connection pooling allows you to easily m

shado 2 Apr 30, 2022
Xr - Lightweight debug server utility built on ReactPHP.

XR ?? Subscribe to the newsletter to don't miss any update regarding Chevere. XR is a dump server utility built on top of ReactPHP. Features ✨ Dump si

Chevere 195 Dec 17, 2022
Event-driven, streaming HTTP client and server implementation for ReactPHP

HTTP Event-driven, streaming HTTP client and server implementation for ReactPHP. This HTTP library provides re-usable implementations for an HTTP clie

ReactPHP 640 Dec 29, 2022
Async MySQL database client for ReactPHP.

MySQL Async MySQL database client for ReactPHP. This is a MySQL database driver for ReactPHP. It implements the MySQL protocol and allows you to acces

Friends of ReactPHP 302 Dec 11, 2022