|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Http\Adapter; |
| 4 | + |
| 5 | +use FOS\HttpCache\Exception\ProxyUnreachableException; |
| 6 | +use GuzzleHttp\Client; |
| 7 | +use GuzzleHttp\Exception\RequestException; |
| 8 | +use GuzzleHttp\Exception\TransferException; |
| 9 | +use GuzzleHttp\Pool; |
| 10 | +use GuzzleHttp\Promise\Promise; |
| 11 | +use Http\Adapter\Common\Exception\HttpAdapterException; |
| 12 | +use Http\Adapter\Common\Exception\MultiHttpAdapterException; |
| 13 | +use Psr\Http\Message\RequestInterface; |
| 14 | +use Psr\Http\Message\ResponseInterface; |
| 15 | + |
| 16 | +class Guzzle6HttpAdapter implements PsrHttpAdapter |
| 17 | +{ |
| 18 | + public function __construct(Client $client = null) |
| 19 | + { |
| 20 | + $this->client = $client ?: new Client(); |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * {@inheritdoc} |
| 25 | + */ |
| 26 | + public function sendRequest(RequestInterface $request) |
| 27 | + { |
| 28 | + try { |
| 29 | + return $this->client->send($request); |
| 30 | + } catch (TransferException $e) { |
| 31 | + throw ProxyUnreachableException::proxyUnreachable($request, $e); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Sends PSR requests |
| 37 | + * |
| 38 | + * @param RequestInterface[] $requests |
| 39 | + * |
| 40 | + * @return ResponseInterface[] |
| 41 | + * |
| 42 | + * @throws \InvalidArgumentException |
| 43 | + * @throws Exception\MultiHttpAdapterException |
| 44 | + */ |
| 45 | + public function sendRequests(array $requests) |
| 46 | + { |
| 47 | + $results = Pool::batch( |
| 48 | + $this->client, |
| 49 | + $requests |
| 50 | + ); |
| 51 | + |
| 52 | + $exceptions = []; |
| 53 | + foreach ($results as $result) { |
| 54 | + if ($result instanceof RequestException) { |
| 55 | + $exception = new HttpAdapterException( |
| 56 | + $result->getMessage(), |
| 57 | + 0, |
| 58 | + $result |
| 59 | + ); |
| 60 | + $exception->setResponse($result->getResponse()); |
| 61 | + $exception->setRequest($result->getRequest()); |
| 62 | + |
| 63 | + $exceptions[] = $exception; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + if (count($exceptions) > 0) { |
| 68 | + throw new MultiHttpAdapterException($exceptions); |
| 69 | + } |
| 70 | + |
| 71 | + return $results; |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * Returns the name |
| 76 | + * |
| 77 | + * @return string |
| 78 | + */ |
| 79 | + public function getName() |
| 80 | + { |
| 81 | + return 'guzzle6'; |
| 82 | + } |
| 83 | +} |
0 commit comments