function it_returns_the_response_on_success(HttpClient $client, RequestInterface $request, ResponseInterface $response) { $client->sendRequest($request)->willReturn($response); $response->getStatusCode()->willReturn(200); $response->getBody()->willReturn('body'); $this->executeRequest($request, array(200))->shouldReturn($response); }
/** * {@inheritdoc} */ public function expand($url) { $url = sprintf('%s/expand?%s', self::ENDPOINT, http_build_query(['access_token' => $this->accessToken, 'shortUrl' => trim($url)])); $request = $this->requestFactory->createRequest('GET', $url); $response = $this->httpClient->sendRequest($request); $response = json_decode((string) $response->getBody()); return $response->data->expand[0]->long_url; }
function it_expands_a_url(RequestFactory $requestFactory, RequestInterface $request, HttpClient $httpClient, ResponseInterface $response, StreamInterface $body) { $requestFactory->createRequest('GET', 'https://api-ssl.bitly.com/v3/expand?access_token=access_token&shortUrl=' . urlencode('http://bit.ly/shortened'))->willReturn($request); $httpClient->sendRequest($request)->willReturn($response); $response->getBody()->willReturn($body); $body->__toString()->willReturn('{"data": {"expand": [{"long_url": "http://any.url"}]}}'); $this->expand('http://bit.ly/shortened')->shouldReturn("http://any.url"); }
function it_should_throw_exception_if_response_is_not_correct_for_finishing_the_verification_process(Response $response, StreamInterface $stream) { $response->getStatusCode()->willReturn(500); $response->getBody()->willReturn($stream); $stream->getContents()->willReturn('Error'); $this->client->sendRequest(Argument::type(Request::class))->shouldBeCalledTimes(1)->willReturn($response); $this->shouldThrow(PactException::class)->during('finishProviderVerificationProcess'); }
function it_expands_a_url(RequestFactory $requestFactory, RequestInterface $request, HttpClient $httpClient, ResponseInterface $response, StreamInterface $body) { $requestFactory->createRequest('GET', 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=' . urlencode('http://goo.gl/shortened'))->willReturn($request); $httpClient->sendRequest($request)->willReturn($response); $response->getBody()->willReturn($body); $body->__toString()->willReturn('{"longUrl": "http://any.url"}'); $this->expand('http://goo.gl/shortened')->shouldReturn("http://any.url"); }
/** * {@inheritdoc} */ public function expand($url) { $url = sprintf('%s?%s', self::ENDPOINT, http_build_query(['key' => $this->apiKey, 'shortUrl' => $url])); $request = $this->requestFactory->createRequest('GET', $url); $response = $this->httpClient->sendRequest($request); $response = json_decode((string) $response->getBody()); return $response->longUrl; }
function it_throws_exception_when_request_returns_not_found_error(HttpClientInterface $httpClient, RequestFactoryInterface $requestFactory, RequestInterface $request, ResponseInterface $response, HttpException $httpException) { $apiHttpPathAndQuery = ApiHttpPathAndQuery::createForPath(self::API_PATH); $response->getStatusCode()->willReturn(404); $requestFactory->createRequest(Argument::any(), Argument::any(), Argument::any())->willReturn($request); $httpException->getResponse()->willReturn($response); $httpClient->sendRequest($request)->willThrow($httpException->getWrappedObject()); $this->shouldThrow(ApiHttpClientNotFoundException::class)->duringGet($apiHttpPathAndQuery); }
function it_expands_a_url(RequestFactory $requestFactory, RequestInterface $request, HttpClient $httpClient, ResponseInterface $response, StreamInterface $body) { $params = array_merge($this->params, ['m' => 'expand', 'shortUrl' => 'http://tiny.cc/shortened']); $requestFactory->createRequest('GET', sprintf('http://tiny.cc?%s', http_build_query($params)))->willReturn($request); $httpClient->sendRequest($request)->willReturn($response); $response->getBody()->willReturn($body); $body->__toString()->willReturn('{"results": {"longUrl": "http://any.url"}}'); $this->expand('http://tiny.cc/shortened')->shouldReturn("http://any.url"); }
/** * Makes an http request to the api. * * @param RequestInterface $request * * @throws HttpException * * @return ResponseInterface */ protected function sendRequest(RequestInterface $request) { try { $response = $this->client->sendRequest($request); } catch (Exception $e) { throw new HttpException($e->getMessage(), $e->getCode()); } return $response; }
/** * Call an API endpoint. * * @param string $someArgument * * @return string */ public function someOperation($someArgument) { $request = $this->messageFactory->createRequest('GET', self::ENDPOINT . '/some_operation?argument=' . $someArgument); try { $response = $this->httpClient->sendRequest($request); } catch (\Http\Client\Exception $e) { throw new \RuntimeException('Something happened during HTTP request'); } return (string) $response->getBody(); }
/** * @param string $token * @param string $message * @return string * @throws InvalidArgumentException * @throws HttpClientException * @throws Exception */ public function snitch($token, $message = "") { $token = new Token($token); $message = new Message($message); $userAgent = (new UserAgent(Version::VERSION))->create(); $requestFactory = new SnitcherRequestFactory($this->messageFactory, $this->streamFactory, $userAgent); $request = $requestFactory->createSnitcherRequest($this->createUriFromToken($token), $message); $response = $this->httpClient->sendRequest($request); $contents = $this->getContentsFromResponse($response); return $contents; }
/** * @param callable $callback */ public function listenEvents(callable $callback) { $request = $this->messageFactory->createRequest('GET', '/events'); $response = $this->httpClient->sendRequest($request); $stream = $response->getBody(); while (!$stream->eof()) { $line = \GuzzleHttp\Psr7\readline($stream); if (null !== ($raw = json_decode($line, true))) { call_user_func($callback, new Event($raw)); } } }
/** * {@inheritdoc} */ public function request($method, $path, array $params = []) { list($params, $files) = $this->splitParams($params); $url = $this->url . $path; try { $request = $this->createRequest($params, $files, $method, $url); $response = $this->adapter->sendRequest($request); return json_decode($response->getBody(), true); } catch (PlugException $e) { throw $this->buildRequestError($e); } }
public function testSearch() { $searchOptions = (new SearchOptions())->withQuery(new Query('Vindicator'))->withSorting(SortField::MINIMUM_LEVEL()); $expectedQueryString = 'query=Vindicator&sortorder=minimum_level_asc'; $expectedUri = (new Uri('items'))->withQuery($expectedQueryString); $request = new Request('GET', $expectedUri); $response = new Response(200, [], json_encode($this->getSingleItemResultSetNormalized())); $this->requestFactory->expects($this->once())->method('create')->with('GET', $expectedUri)->willReturn($request); $this->client->expects($this->once())->method('sendRequest')->with($request)->willReturn($response); $resultSet = $this->service->search($searchOptions); $this->assertEquals($this->getSingleItemResultSet(), $resultSet); }
/** * {@inheritdoc} */ public function get(ApiHttpPathAndQuery $apiHttpPathAndQuery) { try { $request = $this->requestFactory->createRequest(self::GET_REQUEST, $this->apiHttpClientConfiguration->buildUri($apiHttpPathAndQuery), $this->apiHttpClientConfiguration->buildHeaders()); $response = $this->httpClient->sendRequest($request); } catch (Exception $exception) { if ($this->isNotFoundError($exception)) { throw new ApiHttpClientNotFoundException($this->apiHttpClientConfiguration->buildUri($apiHttpPathAndQuery)); } throw new ApiHttpClientException($exception->getMessage(), $exception->getCode(), $exception); } return $response->getBody()->getContents(); }
public function version() { $message = new GuzzleMessageFactory(); $request = $message->createRequest('GET', $this->url . 'version'); $result = $this->adapter->sendRequest($request); return new Version($result); }
/** * Removes participant (provider, consumer) from pact-broker * * @param $participantName * * @return ResponseInterface * @throws PactBrokerException */ public function removeParticipant($participantName) { $request = $this->requestBuilder->createRemoveParticipantRequest($this->baseUrl, $participantName); $response = $this->client->sendRequest($request); $this->checkIfResponseIsCorrect($response); return $response; }
/** * Send a DELETE request with JSON-encoded parameters. * * @param string $path Request path. * @param array $parameters POST parameters to be JSON encoded. * @param array $requestHeaders Request headers. * * @return ResponseInterface */ protected function httpDelete($path, array $parameters = [], array $requestHeaders = []) { try { $response = $this->httpClient->sendRequest($this->requestBuilder->create('DELETE', $path, $requestHeaders, $this->createJsonBody($parameters))); } catch (HttplugException\NetworkException $e) { throw HttpServerException::networkError($e); } return $response; }
/** * @param string $method * @param string $uri * @param string|array $body */ public function sendRequest($method, $uri, $body = null) { if (false === $this->hasHost($uri)) { $uri = rtrim($this->host, '/') . '/' . ltrim($uri, '/'); } $this->request = $this->messageFactory->createRequest($method, $uri, $this->requestHeaders, $body); $this->response = $this->httpClient->sendRequest($this->request); if (null !== $this->responseStorage) { $this->responseStorage->writeRawContent((string) $this->response->getBody()); } }
private function sendRequest() { try { $this->response = $this->client->sendRequest($this->getRequest()); } catch (HttpException $e) { $this->response = $e->getResponse(); if ($this->response === null) { throw $e; } } }
public function getAsset(string $assetUri) : StreamInterface { $assetUriParts = parse_url($assetUri); $uri = $this->uri->withUserInfo(''); if (array_key_exists('path', $assetUriParts)) { $uri = $uri->withPath($assetUriParts['path']); } if (array_key_exists('query', $assetUriParts)) { $uri = $uri->withQuery($assetUriParts['query']); } $request = (new Request($uri, 'GET'))->withAddedHeader('User-agent', 'SimpleFM'); $credentials = urldecode($this->uri->getUserInfo()); if ('' !== $credentials) { $request = $request->withAddedHeader('Authorization', sprintf('Basic %s', base64_encode($credentials))); } $response = $this->httpClient->sendRequest($request); if (200 !== (int) $response->getStatusCode()) { throw InvalidResponseException::fromUnsuccessfulResponse($response); } return $response->getBody(); }
/** * Make an asynchronous call to the API * * @param string $operationId The name of your operation as described in the API Schema * @param array $params An array of request parameters * * @return Promise */ public function callAsync($operationId, array $params = []) { if (!$this->client instanceof HttpAsyncClient) { throw new \RuntimeException(sprintf('"%s" does not support async request', get_class($this->client))); } $requestDefinition = $this->schema->getRequestDefinition($operationId); $request = $this->createRequestFromDefinition($requestDefinition, $params); $promise = $this->client->sendAsyncRequest($request); return $promise->then(function (ResponseInterface $response) use($request, $requestDefinition) { return $this->getDataFromResponse($response, $requestDefinition->getResponseDefinition($response->getStatusCode()), $request); }); }
/** * Send outbound data and return inbound one. * * @param RequestInterface $request * * @return ResponseInterface * * @throws \Exception * @throws \Http\Client\Exception * @throws \InvalidArgumentException * @throws InboundTransferException * @throws InvalidArgumentTypeException * @throws SerializeException * @throws UnserializeException * * @since 1.0 */ protected function transfer($request) { $this->checkArgumentType(__METHOD__, 1, RequestInterface::class, $request); try { /* Try to perform real request and get actual response */ $response = $this->httpClient->sendRequest($request); } catch (TransferException $e) { /* In case of failure pushing request to outbound channel */ $this->sendLater($request); $response = $this->getCachedData($request); } return $response; }
/** * @param Url $url * @return \Psr\Http\Message\ResponseInterface * @throws ActorNotFoundException */ private function internalSendRequest(Url $url) { $this->logger->debug('retrieving cdbxml from ' . (string) $url); $request = new Request('GET', (string) $url, ['Accept' => 'application/xml']); $startTime = microtime(true); $response = $this->httpClient->sendRequest($request); $delta = round(microtime(true) - $startTime, 3) * 1000; $this->logger->debug('sendRequest took ' . $delta . ' ms.'); if (200 !== $response->getStatusCode()) { $this->logger->error('Unable to retrieve cdbxml, server responded with ' . $response->getStatusCode() . ' ' . $response->getReasonPhrase()); throw new ActorNotFoundException('Unable to retrieve actor from ' . (string) $url); } return $response; }
private function sendRequest() { $request = $this->getRequest(); if ($this->multipartStreamBuilder !== null) { $request = $request->withBody($this->multipartStreamBuilder->build())->withHeader('Content-Type', 'multipart/form-data;boundary=' . $this->multipartStreamBuilder->getBoundary()); } try { $this->response = $this->client->sendRequest($request); } catch (HttpException $e) { $this->response = $e->getResponse(); if ($this->response === null) { throw $e; } } }
function it_should_format_response_for_pact_retrieve(RequestInterface $request, ResponseInterface $response, ResponseFormatter $responseFormatter) { $providerName = 'providerB'; $consumerName = 'consumerA'; $version = 'latest'; $tagName = 'prod'; $this->requestBuilder->createRetrievePactRequest($this->baseUrl, $consumerName, $providerName, $version, $tagName)->willReturn($request); $this->client->sendRequest($request)->willReturn($response); $response->getStatusCode()->willReturn(200); $response->getHeader('X-Pact-Consumer-Version')->willReturn(['1.2.0']); $responseFormatter->format($response)->willReturn('a'); $contract = $this->retrievePact($providerName, $consumerName, $version, $tagName, $responseFormatter, $responseFormatter); $contract->shouldHaveType(Contract::class); $contract->data()->shouldReturn('a'); $contract->version()->shouldReturn('1.2.0'); }
/** * {@inheritdoc} */ public function request($url, array $options = [], $method = 'GET', $json = true) { try { $options = array_replace(['body' => null, 'headers' => [], 'query' => []], $options); // Prepend the SharePoint Site URL when only the path is passed if (filter_var($url, FILTER_VALIDATE_URL) === false) { $url = $this->getUrl($url); } if (!empty($options['query'])) { $url = sprintf('%s?%s', $url, http_build_query($options['query'])); } $request = $this->message->createRequest($method, $url, $options['headers'], $options['body']); $response = $this->client->sendRequest($request); return $json ? $this->parseResponse($response) : $response; } catch (HttpClientException $e) { throw new SPRuntimeException('Unable to make HTTP request', 0, $e); } }
/** * Request remote API. * * @param array $params Request params. * * @return ApiResponseInterface * * @throws \Exception If processing the request is impossible (eg. bad configuration). * @throws \Http\Client\Exception In case of any HTTP related errors. * @throws \Psr\Cache\InvalidArgumentException */ protected function request(array $params) { $this->getLogger()->debug(sprintf('API call with params: %s', json_encode($params))); $cacheId = $this->composeCacheId($params); if ($this->getCache() && $this->getCache()->hasItem($cacheId)) { $result = $this->getCache()->getItem($cacheId)->get(); if ($result instanceof ApiResponseInterface) { $result->setTakenFromCache(true); $this->getLogger()->debug(sprintf('Using cached result: %s', $result->getBriefResponse())); return $result; } } $request = $this->createRequest($params); try { $response = $this->httpClient->sendRequest($request); } catch (Exception $e) { $this->getLogger()->error(sprintf('HTTP request "%s %s" failed: %s', $request->getMethod(), $request->getUri(), $e->getMessage())); throw $e; } if ($response->getStatusCode() >= 400) { $this->getLogger()->error(sprintf('HTTP request "%s %s" failed: [%d] %s', $request->getMethod(), $request->getUri(), $response->getStatusCode(), $response->getReasonPhrase())); throw new HttpException($response->getReasonPhrase(), $request, $response); } $result = $this->createApiResponse($response); $result->setTakenFromCache(false); if ($this->getCache() && $result->getResponseTtl() > -1) { $item = $this->getCache()->getItem($cacheId); $item->set($result); if ($result->getResponseTtl() > 0) { $item->expiresAfter($result->getResponseTtl()); } $this->getCache()->save($item); } $this->getLogger()->debug(sprintf('Using fresh result: %s', $result->getBriefResponse())); return $result; }
/** * Read News Stories * * @access public * @param mixed $input * @param array $options * @throws RonException * @return array */ public function read($input, array $options = []) { // Fetch input from a URL if ($url = filter_var($input, FILTER_VALIDATE_URL)) { if ($this->client === null || $this->message === null) { throw new RonException('HttpClient and MessageFactory required to fetch data from a URL'); } try { $request = $this->message->createRequest('GET', $url); $response = $this->client->sendRequest($request); $input = $response->getBody()->getContents(); } catch (Exception $e) { throw new RonException($e->getMessage(), $e->getCode(), $e); } } try { $options = array_replace_recursive(['options' => LIBXML_PARSEHUGE | LIBXML_DTDLOAD | LIBXML_NSCLEAN], $options); $stories = []; $this->parser->extract($input, $options, $stories); return $stories; } catch (EssenceException $e) { throw new RonException($e->getMessage(), $e->getCode(), $e); } }
/** * Perform actual HTTP request to service. * * @param string $method HTTP method. * @param string $uri URI. * @param Document $document Document to send to the server. * * @return Document * * @throws \InvalidArgumentException If given document is not supported. * @throws \Mekras\Atom\Exception\RuntimeException In case of XML errors. * @throws \Mekras\OData\Client\Exception\ClientErrorException On client error. * @throws \Mekras\OData\Client\Exception\NetworkException In case of network error. * @throws \Mekras\OData\Client\Exception\RuntimeException On other errors. * @throws \Mekras\OData\Client\Exception\ServerErrorException On server error. * * @since 0.3 */ public function sendRequest($method, $uri, Document $document = null) { $headers = ['DataServiceVersion' => '2.0', 'MaxDataServiceVersion' => '3.0', 'Accept' => 'application/atom+xml,application/atomsvc+xml,application/xml']; if ($document) { $headers['Content-type'] = 'application/atom+xml'; } $uri = str_replace($this->getServiceRootUri(), '', $uri); $uri = '/' . ltrim($uri, '/'); $request = $this->requestFactory->createRequest($method, $this->getServiceRootUri() . $uri, $headers, $document ? $document->getDomDocument()->saveXML() : null); try { $response = $this->httpClient->sendRequest($request); } catch (HttpClientException\NetworkException $e) { throw new NetworkException($e->getMessage(), $e->getCode(), $e); } catch (\Exception $e) { throw new RuntimeException($e->getMessage(), 0, $e); } $version = $response->getHeaderLine('DataServiceVersion'); if ('' === $version) { throw new ServerErrorException('DataServiceVersion header missed'); } $doc = $this->documentFactory->parseXML((string) $response->getBody()); $this->checkResponseForErrors($response, $doc); return $doc; }