public function getException()
 {
     if (!$this->hasException()) {
         return;
     }
     if ($this->exception->hasResponse() && $this->exception->getResponse()->getBody()->getSize() !== null) {
         $this->exception->getResponse()->getBody()->seek(0, SEEK_SET);
     }
     return $this->exception;
 }
 /**
  * Creates a curl http adapter.
  *
  * @param \Ivory\HttpAdapter\ConfigurationInterface|null $configuration  The configuration.
  * @param boolean                                        $checkExtension TRUE if the extension should be checked else FALSE.
  *
  * @throws \Ivory\HttpAdapter\HttpAdapterException If the check extension is enabled and the curl extension is not loaded.
  */
 public function __construct(ConfigurationInterface $configuration = null, $checkExtension = true)
 {
     if ($checkExtension && !function_exists('curl_init')) {
         throw HttpAdapterException::extensionIsNotLoaded('curl', $this->getName());
     }
     parent::__construct($configuration);
 }
Exemple #3
0
 /**
  * {@inheritdoc}
  */
 protected function doSendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $loop = EventLoopFactory::create();
     $dnsResolverFactory = new DnsResolverFactory();
     $httpClientFactory = new HttpClientFactory();
     $error = null;
     $response = null;
     $body = null;
     $request = $httpClientFactory->create($loop, $dnsResolverFactory->createCached('8.8.8.8', $loop))->request($internalRequest->getMethod(), $url = (string) $internalRequest->getUrl(), $this->prepareHeaders($internalRequest, true, true, true));
     $request->on('error', function (\Exception $onError) use(&$error) {
         $error = $onError;
     });
     $request->on('response', function (Response $onResponse) use(&$response, &$body) {
         $onResponse->on('data', function ($data) use(&$body) {
             $body .= $data;
         });
         $response = $onResponse;
     });
     $request->end($this->prepareBody($internalRequest));
     $loop->run();
     if ($error !== null) {
         throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $error->getMessage());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse((int) $response->getCode(), $response->getReasonPhrase(), $response->getVersion(), $response->getHeaders(), BodyNormalizer::normalize($body, $internalRequest->getMethod()));
 }
Exemple #4
0
 /**
  * {@inheritdoc}
  */
 protected function doAttach($stream)
 {
     if (!$stream instanceof StreamInterface) {
         throw HttpAdapterException::streamIsNotValid($stream, get_class($this), 'GuzzleHttp\\Stream\\StreamInterface');
     }
     $this->stream = $stream;
 }
Exemple #5
0
 /**
  * Normalizes an url.
  *
  * @param string|object $url The url.
  *
  * @throws HttpAdapterException If the url is not valid.
  *
  * @return string The normalized url.
  */
 public static function normalize($url)
 {
     $url = (string) $url;
     if (($parts = parse_url($url)) === false || !isset($parts['scheme']) || !isset($parts['host'])) {
         throw HttpAdapterException::urlIsNotValid($url);
     }
     return $url;
 }
 /**
  * {@inheritdoc}
  */
 protected function doSendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $context = stream_context_create(array('http' => array('follow_location' => false, 'max_redirects' => 1, 'ignore_errors' => true, 'timeout' => $this->getConfiguration()->getTimeout(), 'protocol_version' => $internalRequest->getProtocolVersion(), 'method' => $internalRequest->getMethod(), 'header' => $this->prepareHeaders($internalRequest, false), 'content' => $this->prepareBody($internalRequest))));
     list($body, $headers) = $this->process($url = (string) $internalRequest->getUrl(), $context);
     if ($body === false) {
         $error = error_get_last();
         throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $error['message']);
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse(StatusCodeExtractor::extract($headers), ReasonPhraseExtractor::extract($headers), ProtocolVersionExtractor::extract($headers), HeadersNormalizer::normalize($headers), BodyNormalizer::normalize($body, $internalRequest->getMethod()));
 }
Exemple #7
0
 /**
  * {@inheritdoc}
  */
 protected function doSendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $this->client->resetParameters(true)->setConfig(array('httpversion' => $internalRequest->getProtocolVersion(), 'timeout' => $this->getConfiguration()->getTimeout(), 'maxredirects' => 0))->setUri($url = (string) $internalRequest->getUrl())->setMethod($internalRequest->getMethod())->setHeaders($this->prepareHeaders($internalRequest))->setRawData($this->prepareBody($internalRequest));
     try {
         $response = $this->client->request();
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $e->getMessage());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse($response->getStatus(), $response->getMessage(), $response->getVersion(), $response->getHeaders(), BodyNormalizer::normalize(function () use($response) {
         return $response instanceof \Zend_Http_Response_Stream ? $response->getStream() : $response->getBody();
     }, $internalRequest->getMethod()));
 }
Exemple #8
0
 /**
  * {@inheritdoc}
  */
 protected function doAttach($stream)
 {
     if (!is_resource($stream)) {
         throw HttpAdapterException::streamIsNotValid($stream, get_class($this), 'resource');
     }
     $this->resource = $stream;
     $metadata = $this->getMetadata();
     $this->cache['readable'] = isset(self::$modes['read'][$metadata['mode']]);
     $this->cache['writable'] = isset(self::$modes['write'][$metadata['mode']]);
     $this->cache['seekable'] = $metadata['seekable'];
     $this->cache['local'] = stream_is_local($this->resource);
     $this->cache['uri'] = $metadata['uri'];
 }
Exemple #9
0
 /**
  * {@inheritdoc}
  */
 protected function doSendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $this->httpSocket->config['timeout'] = $this->getConfiguration()->getTimeout();
     $request = array('version' => $this->getConfiguration()->getProtocolVersion(), 'redirect' => false, 'uri' => $url = (string) $internalRequest->getUrl(), 'method' => $internalRequest->getMethod(), 'header' => $this->prepareHeaders($internalRequest), 'body' => $this->prepareBody($internalRequest));
     try {
         $response = $this->httpSocket->request($request);
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $e->getMessage());
     }
     if (($error = $this->httpSocket->lastError()) !== null) {
         throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $error);
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse((int) $response->code, $response->reasonPhrase, ProtocolVersionExtractor::extract($response->httpVersion), $response->headers, BodyNormalizer::normalize($response->body, $internalRequest->getMethod()));
 }
 /**
  * {@inheritdoc}
  */
 protected function sendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $body = new Body();
     $body->append($this->prepareBody($internalRequest));
     $request = new Request($internalRequest->getMethod(), $uri = (string) $internalRequest->getUri(), $this->prepareHeaders($internalRequest), $body);
     $httpVersion = $internalRequest->getProtocolVersion() === InternalRequestInterface::PROTOCOL_VERSION_1_0 ? \http\Client\Curl\HTTP_VERSION_1_0 : \http\Client\Curl\HTTP_VERSION_1_1;
     $request->setOptions(array('protocol' => $httpVersion, 'timeout' => $this->getConfiguration()->getTimeout()));
     try {
         $this->client->reset()->enqueue($request)->send();
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUri($uri, $this->getName(), $e->getMessage());
     }
     $response = $this->client->getResponse();
     return $this->getConfiguration()->getMessageFactory()->createResponse($response->getResponseCode(), $response->getHttpVersion(), $response->getHeaders(), $response->getBody()->getResource());
 }
Exemple #11
0
 /**
  * {@inheritdoc}
  */
 protected function sendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $this->browser->getClient()->setTimeout($this->getConfiguration()->getTimeout());
     $this->browser->getClient()->setMaxRedirects(0);
     $request = $this->browser->getMessageFactory()->createRequest($internalRequest->getMethod(), $uri = (string) $internalRequest->getUri());
     $request->setProtocolVersion($internalRequest->getProtocolVersion());
     $request->setHeaders($this->prepareHeaders($internalRequest, false));
     $data = $this->browser->getClient() instanceof AbstractCurl ? $this->prepareContent($internalRequest) : $this->prepareBody($internalRequest);
     $request->setContent($data);
     try {
         $response = $this->browser->send($request);
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUri($uri, $this->getName(), $e->getMessage());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse($response->getStatusCode(), (string) $response->getProtocolVersion(), HeadersNormalizer::normalize($response->getHeaders()), BodyNormalizer::normalize($response->getContent(), $internalRequest->getMethod()));
 }
Exemple #12
0
 /**
  * {@inheritdoc}
  */
 protected function doSendInternalRequest(InternalRequestInterface $internalRequest)
 {
     list($protocol, $host, $port, $path) = $this->parseUrl($url = (string) $internalRequest->getUrl());
     $socket = @stream_socket_client($protocol . '://' . $host . ':' . $port, $errno, $errstr, $this->getConfiguration()->getTimeout());
     if ($socket === false) {
         throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $errstr);
     }
     stream_set_timeout($socket, $this->getConfiguration()->getTimeout());
     fwrite($socket, $this->prepareRequest($internalRequest, $path, $host, $port));
     list($responseHeaders, $body) = $this->parseResponse($socket);
     $hasTimeout = $this->detectTimeout($socket);
     fclose($socket);
     if ($hasTimeout) {
         throw HttpAdapterException::timeoutExceeded($url, $this->getConfiguration()->getTimeout(), $this->getName());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse(StatusCodeExtractor::extract($responseHeaders), ReasonPhraseExtractor::extract($responseHeaders), ProtocolVersionExtractor::extract($responseHeaders), $responseHeaders = HeadersNormalizer::normalize($responseHeaders), BodyNormalizer::normalize($this->decodeBody($responseHeaders, $body), $internalRequest->getMethod()));
 }
 /**
  * {@inheritdoc}
  */
 protected function sendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $request = new Request();
     foreach ($this->prepareHeaders($internalRequest) as $name => $value) {
         $request->header($name, $value);
     }
     $request->method($internalRequest->getMethod());
     $request->body($this->prepareBody($internalRequest));
     $request->url($uri = (string) $internalRequest->getUri());
     $request->version($this->getConfiguration()->getProtocolVersion());
     try {
         $response = $this->client->send($request, array('timeout' => $this->getConfiguration()->getTimeout(), 'redirect' => false));
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUri($uri, $this->getName(), $e->getMessage());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse((int) $response->statusCode(), $response->version(), $response->headers(), $response->body());
 }
 /**
  * {@inheritdoc}
  */
 protected function sendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $uri = $internalRequest->getUri();
     $socket = @stream_socket_client(($uri->getScheme() === 'https' ? 'ssl' : 'tcp') . '://' . $uri->getHost() . ':' . ($uri->getPort() ?: 80), $errno, $errstr, $this->getConfiguration()->getTimeout());
     if ($socket === false) {
         throw HttpAdapterException::cannotFetchUri($uri, $this->getName(), $errstr);
     }
     stream_set_timeout($socket, $this->getConfiguration()->getTimeout());
     fwrite($socket, $this->prepareRequest($internalRequest));
     list($responseHeaders, $body) = $this->parseResponse($socket);
     $hasTimeout = $this->detectTimeout($socket);
     fclose($socket);
     if ($hasTimeout) {
         throw HttpAdapterException::timeoutExceeded($uri, $this->getConfiguration()->getTimeout(), $this->getName());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse(StatusCodeExtractor::extract($responseHeaders), ProtocolVersionExtractor::extract($responseHeaders), $responseHeaders = HeadersNormalizer::normalize($responseHeaders), BodyNormalizer::normalize($this->decodeBody($responseHeaders, $body), $internalRequest->getMethod()));
 }
 /**
  * {@inheritdoc}
  */
 protected function sendInternalRequests(array $internalRequests, $success, $error)
 {
     $requests = array();
     foreach ($internalRequests as $key => $internalRequest) {
         $requests[$key] = $this->createRequest($internalRequest);
     }
     $httpAdapter = $this;
     $pool = new Pool($this->client, $requests, array_merge($this->createOptions(), array('fulfilled' => function ($response, $index) use($success, $internalRequests, $httpAdapter) {
         $response = $httpAdapter->getConfiguration()->getMessageFactory()->createResponse((int) $response->getStatusCode(), $response->getProtocolVersion(), $response->getHeaders(), BodyNormalizer::normalize(function () use($response) {
             return $response->getBody()->detach();
         }, $internalRequests[$index]->getMethod()));
         $response = $response->withParameter('request', $internalRequests[$index]);
         call_user_func($success, $response);
     }, 'rejected' => function ($exception, $index) use($error, $internalRequests, $httpAdapter) {
         $exception = HttpAdapterException::cannotFetchUri($exception->getRequest()->getUri(), $httpAdapter->getName(), $exception->getMessage());
         $exception->setRequest($internalRequests[$index]);
         call_user_func($error, $exception);
     })));
     $pool->promise()->wait();
 }
Exemple #16
0
 /**
  * {@inheritdoc}
  */
 protected function doSendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $request = Request::init($internalRequest->getMethod())->whenError(function () {
     })->addOnCurlOption(CURLOPT_HTTP_VERSION, $this->prepareProtocolVersion($internalRequest))->timeout($this->getConfiguration()->getTimeout())->uri($url = (string) $internalRequest->getUrl())->addHeaders($this->prepareHeaders($internalRequest))->body($this->prepareContent($internalRequest));
     if (defined('CURLOPT_CONNECTTIMEOUT_MS')) {
         $request->addOnCurlOption(CURLOPT_CONNECTTIMEOUT_MS, $this->getConfiguration()->getTimeout() * 1000);
     } else {
         // @codeCoverageIgnoreStart
         $request->addOnCurlOption(CURLOPT_CONNECTTIMEOUT, $this->getConfiguration()->getTimeout());
     }
     // @codeCoverageIgnoreEnd
     if ($internalRequest->hasFiles()) {
         $request->mime(Mime::UPLOAD);
     }
     try {
         $response = $request->send();
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $e->getMessage());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse($response->code, ReasonPhraseExtractor::extract($response->raw_headers), ProtocolVersionExtractor::extract($response->raw_headers), $response->headers->toArray(), BodyNormalizer::normalize($response->body, $internalRequest->getMethod()));
 }
 /**
  * Creates a response.
  *
  * @param resource                                            $curl            The curl resource.
  * @param string|boolean|null                                 $data            The data.
  * @param \Ivory\HttpAdapter\Message\InternalRequestInterface $internalRequest The internal request.
  *
  * @throws \Ivory\HttpAdapter\HttpAdapterException If an error occurred.
  *
  * @return \Ivory\HttpAdapter\Message\ResponseInterface The response.
  */
 private function createResponse($curl, $data, InternalRequestInterface $internalRequest)
 {
     if (empty($data)) {
         throw HttpAdapterException::cannotFetchUri((string) $internalRequest->getUri(), $this->getName(), curl_error($curl));
     }
     $headers = substr($data, 0, $headersSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE));
     return $this->getConfiguration()->getMessageFactory()->createResponse(StatusCodeExtractor::extract($headers), ProtocolVersionExtractor::extract($headers), HeadersNormalizer::normalize($headers), BodyNormalizer::normalize(substr($data, $headersSize), $internalRequest->getMethod()));
 }
Exemple #18
0
 /**
  * {@inheritdoc}
  */
 public function createRedirectRequest(ResponseInterface $response, InternalRequestInterface $internalRequest, HttpAdapterInterface $httpAdapter)
 {
     if ($response->getStatusCode() < 300 || $response->getStatusCode() >= 400 || !$response->hasHeader('Location')) {
         return false;
     }
     if ($internalRequest->getParameter(self::REDIRECT_COUNT) >= $this->max) {
         if ($this->throwException) {
             $rootRequest = $this->getRootRequest($internalRequest);
             $exception = HttpAdapterException::maxRedirectsExceeded((string) $rootRequest->getUri(), $this->max, $httpAdapter->getName());
             $exception->setRequest($rootRequest);
             throw $exception;
         }
         return false;
     }
     $strict = $response->getStatusCode() === 303 || !$this->strict && $response->getStatusCode() <= 302;
     $headers = $internalRequest->getHeaders();
     foreach ($headers as $key => $value) {
         if (strtolower($key) === 'host') {
             unset($headers[$key]);
         }
     }
     $redirect = $httpAdapter->getConfiguration()->getMessageFactory()->createInternalRequest($response->getHeaderLine('Location'), $strict ? InternalRequestInterface::METHOD_GET : $internalRequest->getMethod(), $internalRequest->getProtocolVersion(), $headers, $strict ? array() : $internalRequest->getDatas(), $strict ? array() : $internalRequest->getFiles(), $internalRequest->getParameters());
     if ($strict) {
         $redirect = $redirect->withoutHeader('Content-Type')->withoutHeader('Content-Length');
     } else {
         $redirect = $redirect->withBody($internalRequest->getBody());
     }
     return $redirect->withParameter(self::PARENT_REQUEST, $internalRequest)->withParameter(self::REDIRECT_COUNT, $internalRequest->getParameter(self::REDIRECT_COUNT) + 1);
 }
 /**
  * Gets an HttpAdapterException from an array.
  *
  * @param array $data
  *
  * @return HttpAdapterException
  */
 public function arrayToException(array $data)
 {
     $exception = new HttpAdapterException($data['message'], $data['code']);
     if (isset($data['request'])) {
         $exception->setRequest($this->arrayToInternalRequest($data['request']));
     }
     if (isset($data['response'])) {
         $exception->setResponse($this->arrayToResponse($data['response']));
     }
     return $exception;
 }
 private function prepareFixtureFile($methodName)
 {
     $tape = $this->createTape($methodName);
     $httpAdapter = HttpAdapterFactory::guess();
     $request = $httpAdapter->getConfiguration()->getMessageFactory()->createRequest('http://httpstat.us/200');
     $response = $httpAdapter->sendRequest($request);
     $exception = new HttpAdapterException();
     $exception->setRequest($httpAdapter->getConfiguration()->getMessageFactory()->createInternalRequest('http://httpstat.us/200'));
     $exception->setResponse($response);
     $track = new Track($request);
     $track->setResponse($response);
     $track->setException($exception);
     $tape->writeTrack($track);
     $tape->store();
 }
Exemple #21
0
 /**
  * {@inheritdoc}
  */
 public function formatException(HttpAdapterException $exception)
 {
     return array('code' => $exception->getCode(), 'message' => $exception->getMessage(), 'line' => $exception->getLine(), 'file' => $exception->getFile());
 }
Exemple #22
0
 /**
  * {@inheritdoc}
  */
 public function addFile($name, $file)
 {
     if ($this->hasRawDatas()) {
         throw HttpAdapterException::doesNotSupportRawDatasAndFiles();
     }
     $this->files[$name] = $this->hasFile($name) ? array_merge((array) $this->files[$name], (array) $file) : $file;
 }
 /**
  * Collects an exception.
  *
  * @param \Ivory\HttpAdapter\HttpAdapterInterface $httpAdapter The http adapter.
  * @param \Ivory\HttpAdapter\HttpAdapterException $exception   The exception.
  */
 private function collectException(HttpAdapterInterface $httpAdapter, HttpAdapterException $exception)
 {
     $this->getTimer()->stop($exception->getRequest());
     $this->datas['exceptions'][] = array('adapter' => $httpAdapter->getName(), 'exception' => $this->getFormatter()->formatException($exception), 'request' => $this->getFormatter()->formatRequest($exception->getRequest()), 'response' => $exception->hasResponse() ? $this->getFormatter()->formatResponse($exception->getResponse()) : null);
 }
 /**
  * @param InternalRequestInterface $request
  * @param ResponseInterface        $response
  *
  * @return HttpAdapterException
  */
 protected function createException(InternalRequestInterface $request = null, ResponseInterface $response = null)
 {
     $request = $request ?: $this->createInternalRequest();
     $response = $response ?: $this->createResponse();
     $e = new HttpAdapterException();
     $e->setRequest($request);
     $e->setResponse($response);
     return $e;
 }
 public function test_it_throws_protocol_exception_from_http_adapter()
 {
     $this->given($SUT = new SUT($this->mockAdapter, $this->apiKey), $httpAdapterException = \Ivory\HttpAdapter\HttpAdapterException::cannotFetchUri('http://www.google.com', get_class($this->mockAdapter), 'this is an error message'), $this->calling($this->mockAdapter)->get->throw = $httpAdapterException)->then($this->exception(function () use($SUT) {
         $SUT->executeQuery([]);
     })->isInstanceOf('Rezzza\\GoogleGeocoder\\Exception\\GoogleGeocodeProtocolException')->hasMessage('An error occurred when fetching the URI "http://www.google.com" with the adapter "mock\\Ivory\\HttpAdapter\\CurlHttpAdapter" ("this is an error message").'))->and($this->mock($this->mockAdapter)->call('get')->once());
 }
 /**
  * Creates a request.
  *
  * @param \Ivory\HttpAdapter\Message\InternalRequestInterface $internalRequest The internal request.
  * @param callable|null                                       $success         The success callable.
  * @param callable|null                                       $error           The error callable.
  *
  * @return \GuzzleHttp\Message\RequestInterface The request.
  */
 private function createRequest(InternalRequestInterface $internalRequest, $success = null, $error = null)
 {
     $request = $this->client->createRequest($internalRequest->getMethod(), (string) $internalRequest->getUrl(), array('exceptions' => false, 'allow_redirects' => false, 'timeout' => $this->getConfiguration()->getTimeout(), 'connect_timeout' => $this->getConfiguration()->getTimeout(), 'version' => $internalRequest->getProtocolVersion(), 'headers' => $this->prepareHeaders($internalRequest), 'body' => $this->prepareContent($internalRequest)));
     if (is_callable($success)) {
         $messageFactory = $this->getConfiguration()->getMessageFactory();
         $request->getEmitter()->on('complete', function (CompleteEvent $event) use($success, $internalRequest, $messageFactory) {
             $response = $messageFactory->createResponse((int) $event->getResponse()->getStatusCode(), $event->getResponse()->getReasonPhrase(), $event->getResponse()->getProtocolVersion(), $event->getResponse()->getHeaders(), BodyNormalizer::normalize(function () use($event) {
                 return new GuzzleHttpStream($event->getResponse()->getBody());
             }, $internalRequest->getMethod()));
             $response->setParameter('request', $internalRequest);
             call_user_func($success, $response);
         });
     }
     if (is_callable($error)) {
         $httpAdapterName = $this->getName();
         $request->getEmitter()->on('error', function (ErrorEvent $event) use($error, $internalRequest, $httpAdapterName) {
             $exception = HttpAdapterException::cannotFetchUrl($event->getException()->getRequest()->getUrl(), $httpAdapterName, $event->getException()->getMessage());
             $exception->setRequest($internalRequest);
             call_user_func($error, $exception);
         });
     }
     return $request;
 }
Exemple #27
0
 /**
  * {@inheritdoc}
  */
 public function sendRequests(array $requests)
 {
     $exceptions = array();
     foreach ($requests as $index => &$request) {
         if (is_string($request)) {
             $request = array($request);
         }
         if (is_array($request)) {
             $request = call_user_func_array(array($this->configuration->getMessageFactory(), 'createInternalRequest'), $request);
         }
         if (!$request instanceof OutgoingRequestInterface) {
             $exceptions[] = HttpAdapterException::requestIsNotValid($request);
             unset($requests[$index]);
         } elseif (!$request instanceof InternalRequestInterface) {
             $request = $this->configuration->getMessageFactory()->createInternalRequest($request->getUrl(), $request->getMethod(), $request->getProtocolVersion(), $request->getHeaders(), (string) $request->getBody());
         }
     }
     try {
         $responses = $this->sendInternalRequests($requests);
     } catch (MultiHttpAdapterException $e) {
         $exceptions = array_merge($exceptions, $e->getExceptions());
         $responses = $e->getResponses();
     }
     if (!empty($exceptions)) {
         throw new MultiHttpAdapterException($exceptions, $responses);
     }
     return $responses;
 }
 /**
  * Creates a status code exception.
  *
  * @param \Ivory\HttpAdapter\Message\ResponseInterface        $response        The response.
  * @param \Ivory\HttpAdapter\Message\InternalRequestInterface $internalRequest The internal request.
  * @param \Ivory\HttpAdapter\HttpAdapterInterface             $httpAdapter     The http adapter.
  *
  * @return \Ivory\HttpAdapter\HttpAdapterException The status code exception.
  */
 private function createStatusCodeException(ResponseInterface $response, InternalRequestInterface $internalRequest, HttpAdapterInterface $httpAdapter)
 {
     $exception = HttpAdapterException::cannotFetchUri((string) $internalRequest->getUri(), $httpAdapter->getName(), sprintf('Status code: %d', $response->getStatusCode()));
     $exception->setRequest($internalRequest);
     $exception->setResponse($response);
     return $exception;
 }
Exemple #29
0
 /**
  * @param Ivory\HttpAdapter\HttpAdapterInterface $adapter
  */
 function it_throws_an_exception_when_the_rate_limit_is_exceeded($adapter)
 {
     $stream = new StringStream('"Rate limit exceeded. Only one Yo all once per minute."');
     $response = new Response(400, '', MessageInterface::PROTOCOL_VERSION_1_1, array(), $stream, array());
     $exception = new HttpAdapterException('An error occurred when fetching the URL "https://api.justyo.co/yoall" with the adapter "curl" ("Status code: 400").');
     $exception->setResponse($response);
     $adapter->send(sprintf('%s/yoall/', Yo::ENDPOINT), InternalRequestInterface::METHOD_POST, array(), array('api_token' => self::API_KEY))->willThrow($exception);
     $this->shouldThrow(new \RuntimeException('[Yo] something went wrong `An error occurred when fetching the URL "https://api.justyo.co/yoall" with the adapter "curl" ("Status code: 400").` the response body was `"Rate limit exceeded. Only one Yo all once per minute."` !'))->duringAll();
 }
 /**
  * Logs error.
  *
  * @param \Ivory\HttpAdapter\HttpAdapterInterface $httpAdapter The http adapter.
  * @param \Ivory\HttpAdapter\HttpAdapterException $exception   The exception.
  *
  * @return \Ivory\HttpAdapter\Message\InternalRequestInterface The logged request.
  */
 private function error(HttpAdapterInterface $httpAdapter, HttpAdapterException $exception)
 {
     $request = $this->getTimer()->stop($exception->getRequest());
     $this->logger->error(sprintf('Unable to send "%s %s".', $exception->getRequest()->getMethod(), (string) $exception->getRequest()->getUri()), array('adapter' => $httpAdapter->getName(), 'exception' => $this->getFormatter()->formatException($exception), 'request' => $this->getFormatter()->formatRequest($request), 'response' => $exception->hasResponse() ? $this->getFormatter()->formatResponse($exception->getResponse()) : null));
     return $request;
 }