| 1 |
<?php |
| 2 |
namespace Aws\Handler\Guzzle; |
| 3 |
|
| 4 |
use Exception; |
| 5 |
use GuzzleHttp\Exception\ConnectException; |
| 6 |
use GuzzleHttp\Exception\RequestException; |
| 7 |
use GuzzleHttp\Utils; |
| 8 |
use GuzzleHttp\Promise; |
| 9 |
use GuzzleHttp\Client; |
| 10 |
use GuzzleHttp\ClientInterface; |
| 11 |
use GuzzleHttp\TransferStats; |
| 12 |
use Psr\Http\Message\RequestInterface as Psr7Request; |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
class GuzzleHandler |
| 18 |
{ |
| 19 |
|
| 20 |
private $client; |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
public function __construct(?ClientInterface $client = null) |
| 26 |
{ |
| 27 |
$this->client = $client ?: new Client(); |
| 28 |
} |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
public function __invoke(Psr7Request $request, array $options = []) |
| 37 |
{ |
| 38 |
$request = $request->withHeader( |
| 39 |
'User-Agent', |
| 40 |
$request->getHeaderLine('User-Agent') |
| 41 |
. ' ' . Utils::defaultUserAgent() |
| 42 |
); |
| 43 |
|
| 44 |
return $this->client->sendAsync($request, $this->parseOptions($options)) |
| 45 |
->otherwise( |
| 46 |
static function ($e) { |
| 47 |
$error = [ |
| 48 |
'exception' => $e, |
| 49 |
'connection_error' => $e instanceof ConnectException, |
| 50 |
'response' => null, |
| 51 |
]; |
| 52 |
|
| 53 |
if ( |
| 54 |
($e instanceof RequestException) |
| 55 |
&& $e->getResponse() |
| 56 |
) { |
| 57 |
$error['response'] = $e->getResponse(); |
| 58 |
} |
| 59 |
|
| 60 |
return new Promise\RejectedPromise($error); |
| 61 |
} |
| 62 |
); |
| 63 |
} |
| 64 |
|
| 65 |
private function parseOptions(array $options) |
| 66 |
{ |
| 67 |
if (isset($options['http_stats_receiver'])) { |
| 68 |
$fn = $options['http_stats_receiver']; |
| 69 |
unset($options['http_stats_receiver']); |
| 70 |
|
| 71 |
$prev = isset($options['on_stats']) |
| 72 |
? $options['on_stats'] |
| 73 |
: null; |
| 74 |
|
| 75 |
$options['on_stats'] = static function ( |
| 76 |
TransferStats $stats |
| 77 |
) use ($fn, $prev) { |
| 78 |
if (is_callable($prev)) { |
| 79 |
$prev($stats); |
| 80 |
} |
| 81 |
$transferStats = ['total_time' => $stats->getTransferTime()]; |
| 82 |
$transferStats += $stats->getHandlerStats(); |
| 83 |
$fn($transferStats); |
| 84 |
}; |
| 85 |
} |
| 86 |
|
| 87 |
return $options; |
| 88 |
} |
| 89 |
} |