| 1 |
<?php |
| 2 |
|
| 3 |
namespace Dudlewebs\WPMCS\s3\Aws\Handler\Guzzle; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
use Dudlewebs\WPMCS\s3\GuzzleHttp\Exception\ConnectException; |
| 7 |
use Dudlewebs\WPMCS\s3\GuzzleHttp\Exception\RequestException; |
| 8 |
use Dudlewebs\WPMCS\s3\GuzzleHttp\Utils; |
| 9 |
use Dudlewebs\WPMCS\s3\GuzzleHttp\Promise; |
| 10 |
use Dudlewebs\WPMCS\s3\GuzzleHttp\Client; |
| 11 |
use Dudlewebs\WPMCS\s3\GuzzleHttp\ClientInterface; |
| 12 |
use Dudlewebs\WPMCS\s3\GuzzleHttp\TransferStats; |
| 13 |
use Dudlewebs\WPMCS\s3\Psr\Http\Message\RequestInterface as Psr7Request; |
| 14 |
/** |
| 15 |
* A request handler that sends PSR-7-compatible requests with Guzzle. |
| 16 |
*/ |
| 17 |
class GuzzleHandler |
| 18 |
{ |
| 19 |
/** @var ClientInterface */ |
| 20 |
private $client; |
| 21 |
/** |
| 22 |
* @param ClientInterface $client |
| 23 |
*/ |
| 24 |
public function __construct(?ClientInterface $client = null) |
| 25 |
{ |
| 26 |
$this->client = $client ?: new Client(); |
| 27 |
} |
| 28 |
/** |
| 29 |
* @param Psr7Request $request |
| 30 |
* @param array $options |
| 31 |
* |
| 32 |
* @return Promise\Promise |
| 33 |
*/ |
| 34 |
public function __invoke(Psr7Request $request, array $options = []) |
| 35 |
{ |
| 36 |
$request = $request->withHeader('User-Agent', $request->getHeaderLine('User-Agent') . ' ' . Utils::defaultUserAgent()); |
| 37 |
return $this->client->sendAsync($request, $this->parseOptions($options))->otherwise(static function ($e) { |
| 38 |
$error = ['exception' => $e, 'connection_error' => $e instanceof ConnectException, 'response' => null]; |
| 39 |
if ($e instanceof RequestException && $e->getResponse()) { |
| 40 |
$error['response'] = $e->getResponse(); |
| 41 |
} |
| 42 |
return new Promise\RejectedPromise($error); |
| 43 |
}); |
| 44 |
} |
| 45 |
private function parseOptions(array $options) |
| 46 |
{ |
| 47 |
if (isset($options['http_stats_receiver'])) { |
| 48 |
$fn = $options['http_stats_receiver']; |
| 49 |
unset($options['http_stats_receiver']); |
| 50 |
$prev = isset($options['on_stats']) ? $options['on_stats'] : null; |
| 51 |
$options['on_stats'] = static function (TransferStats $stats) use($fn, $prev) { |
| 52 |
if (\is_callable($prev)) { |
| 53 |
$prev($stats); |
| 54 |
} |
| 55 |
$transferStats = ['total_time' => $stats->getTransferTime()]; |
| 56 |
$transferStats += $stats->getHandlerStats(); |
| 57 |
$fn($transferStats); |
| 58 |
}; |
| 59 |
} |
| 60 |
return $options; |
| 61 |
} |
| 62 |
} |
| 63 |
|