2019-06-10 12:49:36 +01:00
< ? php
/*
* This file is part of the Symfony package .
*
* ( c ) Fabien Potencier < fabien @ symfony . com >
*
* For the full copyright and license information , please view the LICENSE
* file that was distributed with this source code .
*/
namespace Symfony\Component\HttpClient ;
2019-09-26 10:41:29 +01:00
use GuzzleHttp\Promise\Promise as GuzzlePromise ;
2019-06-10 12:49:36 +01:00
use Http\Client\Exception\NetworkException ;
use Http\Client\Exception\RequestException ;
2019-09-26 10:41:29 +01:00
use Http\Client\HttpAsyncClient ;
use Http\Client\HttpClient as HttplugInterface ;
2019-06-10 12:49:36 +01:00
use Http\Message\RequestFactory ;
use Http\Message\StreamFactory ;
use Http\Message\UriFactory ;
2019-09-26 10:41:29 +01:00
use Http\Promise\Promise ;
use Http\Promise\RejectedPromise ;
use Nyholm\Psr7\Factory\Psr17Factory ;
use Nyholm\Psr7\Request ;
use Nyholm\Psr7\Uri ;
use Psr\Http\Message\RequestFactoryInterface ;
2019-06-10 12:49:36 +01:00
use Psr\Http\Message\RequestInterface ;
use Psr\Http\Message\ResponseFactoryInterface ;
2019-09-26 10:41:29 +01:00
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface ;
2019-06-10 12:49:36 +01:00
use Psr\Http\Message\StreamFactoryInterface ;
use Psr\Http\Message\StreamInterface ;
2019-09-26 10:41:29 +01:00
use Psr\Http\Message\UriFactoryInterface ;
2019-06-10 12:49:36 +01:00
use Psr\Http\Message\UriInterface ;
2019-09-26 10:41:29 +01:00
use Symfony\Component\HttpClient\Response\HttplugPromise ;
use Symfony\Component\HttpClient\Response\ResponseTrait ;
use Symfony\Component\HttpClient\Response\StreamWrapper ;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface ;
2019-06-10 12:49:36 +01:00
use Symfony\Contracts\HttpClient\HttpClientInterface ;
2019-09-26 10:41:29 +01:00
use Symfony\Contracts\HttpClient\ResponseInterface ;
2019-06-10 12:49:36 +01:00
2019-09-26 10:41:29 +01:00
if ( ! interface_exists ( HttplugInterface :: class )) {
2019-06-10 12:49:36 +01:00
throw new \LogicException ( 'You cannot use "Symfony\Component\HttpClient\HttplugClient" as the "php-http/httplug" package is not installed. Try running "composer require php-http/httplug".' );
}
if ( ! interface_exists ( RequestFactory :: class )) {
throw new \LogicException ( 'You cannot use "Symfony\Component\HttpClient\HttplugClient" as the "php-http/message-factory" package is not installed. Try running "composer require nyholm/psr7".' );
}
/**
* An adapter to turn a Symfony HttpClientInterface into an Httplug client .
*
2019-09-26 10:41:29 +01:00
* Run " composer require nyholm/psr7 " to install an efficient implementation of response
2019-06-10 12:49:36 +01:00
* and stream factories with flex - provided autowiring aliases .
*
* @ author Nicolas Grekas < p @ tchwork . com >
*/
2019-09-26 10:41:29 +01:00
final class HttplugClient implements HttplugInterface , HttpAsyncClient , RequestFactory , StreamFactory , UriFactory
2019-06-10 12:49:36 +01:00
{
private $client ;
2019-09-26 10:41:29 +01:00
private $responseFactory ;
private $streamFactory ;
private $promisePool = [];
private $pendingResponse ;
2019-06-10 12:49:36 +01:00
public function __construct ( HttpClientInterface $client = null , ResponseFactoryInterface $responseFactory = null , StreamFactoryInterface $streamFactory = null )
{
2019-09-26 10:41:29 +01:00
$this -> client = $client ? ? HttpClient :: create ();
$this -> responseFactory = $responseFactory ;
$this -> streamFactory = $streamFactory ? ? ( $responseFactory instanceof StreamFactoryInterface ? $responseFactory : null );
$this -> promisePool = new \SplObjectStorage ();
if ( null !== $this -> responseFactory && null !== $this -> streamFactory ) {
return ;
}
if ( ! class_exists ( Psr17Factory :: class )) {
throw new \LogicException ( 'You cannot use the "Symfony\Component\HttpClient\HttplugClient" as no PSR-17 factories have been provided. Try running "composer require nyholm/psr7".' );
}
$psr17Factory = new Psr17Factory ();
$this -> responseFactory = $this -> responseFactory ? ? $psr17Factory ;
$this -> streamFactory = $this -> streamFactory ? ? $psr17Factory ;
2019-06-10 12:49:36 +01:00
}
/**
* { @ inheritdoc }
*/
2019-09-26 10:41:29 +01:00
public function sendRequest ( RequestInterface $request ) : Psr7ResponseInterface
2019-06-10 12:49:36 +01:00
{
try {
2019-09-26 10:41:29 +01:00
return $this -> createPsr7Response ( $this -> sendPsr7Request ( $request ));
} catch ( TransportExceptionInterface $e ) {
2019-06-10 12:49:36 +01:00
throw new NetworkException ( $e -> getMessage (), $request , $e );
}
}
2019-09-26 10:41:29 +01:00
/**
* { @ inheritdoc }
*
* @ return HttplugPromise
*/
public function sendAsyncRequest ( RequestInterface $request ) : Promise
{
if ( ! class_exists ( GuzzlePromise :: class )) {
throw new \LogicException ( sprintf ( 'You cannot use "%s()" as the "guzzlehttp/promises" package is not installed. Try running "composer require guzzlehttp/promises".' , __METHOD__ ));
}
try {
$response = $this -> sendPsr7Request ( $request , true );
} catch ( NetworkException $e ) {
return new RejectedPromise ( $e );
}
$cancel = function () use ( $response ) {
$response -> cancel ();
unset ( $this -> promisePool [ $response ]);
};
$promise = new GuzzlePromise ( function () use ( $response ) {
$this -> pendingResponse = $response ;
$this -> wait ();
}, $cancel );
$this -> promisePool [ $response ] = [ $request , $promise ];
return new HttplugPromise ( $promise , $cancel );
}
/**
* Resolve pending promises that complete before the timeouts are reached .
*
* When $maxDuration is null and $idleTimeout is reached , promises are rejected .
*
* @ return int The number of remaining pending promises
*/
public function wait ( float $maxDuration = null , float $idleTimeout = null ) : int
{
$pendingResponse = $this -> pendingResponse ;
$this -> pendingResponse = null ;
if ( null !== $maxDuration ) {
$startTime = microtime ( true );
$idleTimeout = max ( 0.0 , min ( $maxDuration / 5 , $idleTimeout ? ? $maxDuration ));
$remainingDuration = $maxDuration ;
}
do {
foreach ( $this -> client -> stream ( $this -> promisePool , $idleTimeout ) as $response => $chunk ) {
try {
if ( null !== $maxDuration && $chunk -> isTimeout ()) {
goto check_duration ;
}
if ( $chunk -> isFirst ()) {
// Deactivate throwing on 3/4/5xx
$response -> getStatusCode ();
}
if ( ! $chunk -> isLast ()) {
goto check_duration ;
}
if ([ $request , $promise ] = $this -> promisePool [ $response ] ? ? null ) {
unset ( $this -> promisePool [ $response ]);
$promise -> resolve ( $this -> createPsr7Response ( $response , true ));
}
} catch ( \Exception $e ) {
if ([ $request , $promise ] = $this -> promisePool [ $response ] ? ? null ) {
unset ( $this -> promisePool [ $response ]);
if ( $e instanceof TransportExceptionInterface ) {
$e = new NetworkException ( $e -> getMessage (), $request , $e );
}
$promise -> reject ( $e );
}
}
if ( $pendingResponse === $response ) {
return \count ( $this -> promisePool );
}
check_duration :
if ( null !== $maxDuration && $idleTimeout && $idleTimeout > $remainingDuration = max ( 0.0 , $maxDuration - microtime ( true ) + $startTime )) {
$idleTimeout = $remainingDuration / 5 ;
break ;
}
}
if ( ! $count = \count ( $this -> promisePool )) {
return 0 ;
}
} while ( null !== $maxDuration && 0 < $remainingDuration );
return $count ;
}
2019-06-10 12:49:36 +01:00
/**
* { @ inheritdoc }
*/
public function createRequest ( $method , $uri , array $headers = [], $body = null , $protocolVersion = '1.1' ) : RequestInterface
{
2019-09-26 10:41:29 +01:00
if ( $this -> responseFactory instanceof RequestFactoryInterface ) {
$request = $this -> responseFactory -> createRequest ( $method , $uri );
} elseif ( ! class_exists ( Request :: class )) {
throw new \LogicException ( sprintf ( 'You cannot use "%s()" as the "nyholm/psr7" package is not installed. Try running "composer require nyholm/psr7".' , __METHOD__ ));
} else {
$request = new Request ( $method , $uri );
}
$request = $request
2019-06-10 12:49:36 +01:00
-> withProtocolVersion ( $protocolVersion )
-> withBody ( $this -> createStream ( $body ))
;
foreach ( $headers as $name => $value ) {
$request = $request -> withAddedHeader ( $name , $value );
}
return $request ;
}
/**
* { @ inheritdoc }
*/
public function createStream ( $body = null ) : StreamInterface
{
if ( $body instanceof StreamInterface ) {
return $body ;
}
if ( \is_string ( $body ? ? '' )) {
2019-09-26 10:41:29 +01:00
$stream = $this -> streamFactory -> createStream ( $body ? ? '' );
} elseif ( \is_resource ( $body )) {
$stream = $this -> streamFactory -> createStreamFromResource ( $body );
} else {
throw new \InvalidArgumentException ( sprintf ( '%s() expects string, resource or StreamInterface, %s given.' , __METHOD__ , \gettype ( $body )));
2019-06-10 12:49:36 +01:00
}
2019-09-26 10:41:29 +01:00
if ( $stream -> isSeekable ()) {
$stream -> seek ( 0 );
2019-06-10 12:49:36 +01:00
}
2019-09-26 10:41:29 +01:00
return $stream ;
2019-06-10 12:49:36 +01:00
}
/**
* { @ inheritdoc }
*/
2019-09-26 10:41:29 +01:00
public function createUri ( $uri ) : UriInterface
2019-06-10 12:49:36 +01:00
{
2019-09-26 10:41:29 +01:00
if ( $uri instanceof UriInterface ) {
return $uri ;
}
if ( $this -> responseFactory instanceof UriFactoryInterface ) {
return $this -> responseFactory -> createUri ( $uri );
}
if ( ! class_exists ( Uri :: class )) {
throw new \LogicException ( sprintf ( 'You cannot use "%s()" as the "nyholm/psr7" package is not installed. Try running "composer require nyholm/psr7".' , __METHOD__ ));
}
return new Uri ( $uri );
}
private function sendPsr7Request ( RequestInterface $request , bool $buffer = null ) : ResponseInterface
{
try {
$body = $request -> getBody ();
if ( $body -> isSeekable ()) {
$body -> seek ( 0 );
}
return $this -> client -> request ( $request -> getMethod (), ( string ) $request -> getUri (), [
'headers' => $request -> getHeaders (),
'body' => $body -> getContents (),
'http_version' => '1.0' === $request -> getProtocolVersion () ? '1.0' : null ,
'buffer' => $buffer ,
]);
} catch ( \InvalidArgumentException $e ) {
throw new RequestException ( $e -> getMessage (), $request , $e );
} catch ( TransportExceptionInterface $e ) {
throw new NetworkException ( $e -> getMessage (), $request , $e );
}
}
private function createPsr7Response ( ResponseInterface $response , bool $buffer = false ) : Psr7ResponseInterface
{
$psrResponse = $this -> responseFactory -> createResponse ( $response -> getStatusCode ());
foreach ( $response -> getHeaders ( false ) as $name => $values ) {
foreach ( $values as $value ) {
$psrResponse = $psrResponse -> withAddedHeader ( $name , $value );
}
}
if ( isset ( class_uses ( $response )[ ResponseTrait :: class ])) {
$body = $this -> streamFactory -> createStreamFromResource ( $response -> toStream ( false ));
} elseif ( ! $buffer ) {
$body = $this -> streamFactory -> createStreamFromResource ( StreamWrapper :: createResource ( $response , $this -> client ));
} else {
$body = $this -> streamFactory -> createStream ( $response -> getContent ( false ));
}
if ( $body -> isSeekable ()) {
$body -> seek ( 0 );
}
return $psrResponse -> withBody ( $body );
2019-06-10 12:49:36 +01:00
}
}