Exemplo n.º 1
0
 /**
  * @param string $url
  * @param string $method
  * @param array $options
  * @return \GuzzleHttp\Message\Request
  */
 protected function createRequest($url, $method = 'GET', $options = array())
 {
     // $defaults = array('future' => true, 'debug' => true);
     $defaults = array('future' => true);
     $req = $this->client->createRequest($method, $url, array_merge($defaults, $options));
     return $req;
 }
Exemplo n.º 2
0
 /**
  * Method to handle the Subscribe Request to the Hub
  */
 public function subscribe()
 {
     // Start empty $hubUrl variable
     $hubUrl = '';
     // Check if the Hub URL finishes with a / or not to be able to create the correct subscribe URL
     if (preg_match("/\\/\$/", $this->current_options['hub_url'])) {
         $hubUrl = $this->current_options['hub_url'] . 'subscribe';
     } else {
         $hubUrl = $this->current_options['hub_url'] . '/subscribe';
     }
     // Json Data needed to send to the Hub for Subscription
     $subscribeJson = json_encode(array("callbackUrl" => esc_url($this->callbackUrl), "topicId" => esc_url($this->current_options['topic_url'])), JSON_UNESCAPED_SLASHES);
     $subscribeRequest = $this->guzzleClient->createRequest('POST', $hubUrl);
     $subscribeRequest->setHeader('Content-Type', 'application/json');
     $subscribeRequest->setBody(Stream::factory($subscribeJson));
     $subscribeResponse = $this->guzzleClient->send($subscribeRequest);
     // Check if Response is 200, 202 or 204 and add a log message otherwise log error message
     if (in_array($subscribeResponse->getStatusCode(), array(200, 202, 204))) {
         HubLogger::log('Your Subscription request is being processed. Check back later to see if you are fully Subscribed', $subscribeResponse->getStatusCode());
         return true;
     } else {
         HubLogger::error('Error issuing Subscribe request to the Hub. Please make sure all your details are correct', $subscribeResponse->getStatusCode());
         return false;
     }
 }
Exemplo n.º 3
0
 /**
  * @param IpnEntity $ipn
  * @return bool
  */
 public function forwardIpn(IpnEntity $ipn)
 {
     $urls = $ipn->getForwardUrls();
     if (!empty($urls)) {
         $requests = [];
         foreach ($urls as $url) {
             $request = $this->guzzle->createRequest('post', $url);
             $request->setHeader($this->customHeader, $this->getKey());
             if (in_array($url, $this->disabledJsonFormatting)) {
                 $request->getQuery()->merge($ipn->toArray());
             } else {
                 $request->setHeader('content-type', 'application/json');
                 if ($this->formatter) {
                     $response = $this->formatter->formatJsonResponse($ipn);
                 } else {
                     $response = ['ipn' => $ipn->toArray()];
                 }
                 $request->setBody(Stream::factory(json_encode($response)));
             }
             $requests[] = $request;
         }
         $this->guzzle->sendAll($requests, ['parallel' => $this->maxRequests]);
         return true;
     }
     return false;
 }
Exemplo n.º 4
0
 /**
  * Handles all api calls
  * 
  * @param string $uri
  * @param array $params
  * @return array
  * @throws \Exception
  */
 public function getRequest($uri, array $params = [])
 {
     // validate uri
     if (!is_string($uri)) {
         throw new InvalidArgumentException("Invalid uri {$uri} submitted.");
     }
     // make sure uri isn't absolute - remove first / if there
     if ($uri[0] == '/') {
         $uri = substr($uri, 1);
     }
     try {
         $request = $this->client->createRequest('GET', $uri, ['query' => $params]);
         $response = $this->client->send($request)->json();
         // cairo returns 200 even for errors so check response for error
         // errors array can have multiple, which do we show? create one string for all?
         if (!empty($response['errors'])) {
             throw RequestException::create($request, new Response($response['errors'][0]['code'], [], null, ['reason_phrase' => $response['errors'][0]['messages'][0]]));
         }
     } catch (RequestException $e) {
         $message = $e->getRequest() . "\n";
         if ($e->hasResponse()) {
             $message .= $e->getResponse() . "\n";
         }
         throw new Exception($message, $e->getCode());
     }
     return $response;
 }
Exemplo n.º 5
0
 /**
  * Performs a upload request
  *
  * @param  Request $request
  * @return An array attactment objects
  */
 public function upload(Request $request)
 {
     $this->emit('before.request', [$request, &$this->headers]);
     $files = $request->getFiles();
     if ($files->count() == 0) {
         throw new \UnexpectedValueException("Upload request must have at least one file.");
     }
     $options = ['headers' => $this->headers, 'cookies' => true, 'verify' => false];
     if (!empty($this->_authToken)) {
         $options['cookies'] = array('ZM_AUTH_TOKEN' => $this->_authToken);
     }
     $httpRequest = $this->_httpClient->createRequest('POST', $this->_location, $options);
     $postBody = $httpRequest->getBody();
     $postBody->setField('requestId', $request->getRequestId());
     foreach ($files as $file) {
         $postBody->addFile(new PostFile(basename($file), fopen($file, 'r')));
     }
     $httpRequest->setQuery(['fmt' => 'raw,extended']);
     try {
         $response = $this->_httpClient->send($httpRequest);
         $this->emit('after.request', [$response, $response->getHeaders()]);
     } catch (BadResponseException $ex) {
         if ($ex->hasResponse()) {
             $response = $ex->getResponse();
             $this->emit('after.request', [$response, $response->getHeaders()]);
         }
         throw $ex;
     }
     return $this->_parseResponse($response);
 }
Exemplo n.º 6
0
 /**
  * Guzzle 4 Request method implementation
  *
  * @param string $httpMethod
  * @param string $path
  * @param array $params
  * @param null $version
  * @param bool $isAuthorization
  *
  * @return Response|mixed
  * @throws ClientException
  * @throws AuthorizeException
  * @throws ServerException
  * @throws Error
  */
 public function request($httpMethod = 'GET', $path = '', $params = array(), $version = null, $isAuthorization = false)
 {
     $guzzleClient = new GuzzleClient();
     switch ($httpMethod) {
         case 'GET':
             $request = $guzzleClient->createRequest($httpMethod, $path, array('query' => $params));
             break;
         default:
             $request = $guzzleClient->createRequest($httpMethod, $path, array('body' => $params));
     }
     try {
         $res = $guzzleClient->send($request);
     } catch (GuzzleException\ClientException $e) {
         //catch error 404
         $error_message = $e->getResponse();
         if ($isAuthorization) {
             throw new AuthorizeException($error_message, $e->getCode(), $e->getPrevious());
         } else {
             throw new ClientException($error_message, $e->getCode(), $e->getPrevious());
         }
     } catch (GuzzleException\ServerException $e) {
         throw new ServerException($e, $e->getCode(), $e->getPrevious());
     } catch (GuzzleException\BadResponseException $e) {
         throw new Error($e->getResponse(), $e->getCode(), $e->getPrevious());
     }
     $response = new Response($res->json(), $res->getCode());
     return $response;
 }
Exemplo n.º 7
0
 /**
  * @param string $method
  * @param string $uri
  * @param array  $options
  *
  * @return ResponseInterface
  */
 public function request($method, $uri, array $options = [])
 {
     $this->lazyLoadGuzzle();
     $this->lastRequest = $this->guzzle->createRequest($method, $uri, $options);
     $response = $this->guzzle->send($this->lastRequest);
     return $response;
 }
Exemplo n.º 8
0
 protected function createBaseRequest($accessToken, $method, $baseUrl)
 {
     $request = $this->client->createRequest($method, $baseUrl);
     //        $request->getQuery()->set("api_key", $this->apiKey);
     $request->setHeaders($this->getHeaders($accessToken));
     return $request;
 }
Exemplo n.º 9
0
 /**
  * @return array
  */
 public function doRequest() : array
 {
     $this->generateRequestOptions();
     $this->authenticator->authenticate($this);
     $request = $this->httpClient->createRequest($this->method, $this->getUrl(), $this->requestOptions);
     return $this->httpClient->send($request)->json();
 }
Exemplo n.º 10
0
 /**
  * {@InheritDoc}
  */
 public function send(Request $request)
 {
     $guzzleRequest = $this->client->createRequest($request->getMethod(), $request->getUri(), ['headers' => $request->getHeaders()]);
     $guzzleRequest->setBody(Stream::factory($request->getBody()));
     $guzzleResponse = $this->getClient()->send($guzzleRequest);
     $response = new Response($guzzleResponse->getStatusCode(), $guzzleResponse->getHeaders(), $guzzleResponse->getBody(true));
     return $response;
 }
 protected function sendGuzzleRequest($http_verb = 'GET', $url, $data = null)
 {
     if (date(time()) >= Session::get('oauth_token_expiry')) {
         $this->refreshAccessToken();
     }
     $request = $this->client->createRequest($http_verb, $url, ['json' => $data, 'headers' => ['Authorization' => 'Bearer ' . Session::get('access_token')]]);
     return $this->client->send($request)->json();
 }
 /**
  * Broadcast the given event.
  *
  * @param  array $channels
  * @param  string $event
  * @param  array $payload
  * @return void
  */
 public function broadcast(array $channels, $event, array $payload = array())
 {
     foreach ($channels as $channel) {
         $payload = ['text' => array_merge(['eventtype' => $event], $payload)];
         $request = $this->client->createRequest('POST', '/pub?id=' . $channel, ['json' => $payload]);
         $response = $this->client->send($request);
     }
 }
Exemplo n.º 13
0
 public function execute($method, $uri, $data)
 {
     $request = $this->guzzleClient->createRequest($method, $uri, $data);
     /** @var ResponseInterface $response */
     /** @noinspection PhpVoidFunctionResultUsedInspection */
     $response = $this->guzzleClient->send($request);
     return new Response($response);
 }
 /**
  * @param  Request       $request
  * @return GuzzleRequest
  */
 protected function prepareRequest(Request $request)
 {
     $guzzleRequest = $this->client->createRequest($request->getMethod(), (string) $request->getUrl(), array('version' => $request->getProtocolVersion()));
     if (null !== ($content = $request->getContent())) {
         $guzzleRequest->setBody(Stream::factory($content));
     }
     $guzzleRequest->setHeaders($this->prepareHeaders($request));
     return $guzzleRequest;
 }
 protected function buildBaseRequest()
 {
     $request = $this->client->createRequest(Settings::GET, Settings::BASE_URL . $this->ENDPOINT_URL, Settings::$CREATE_REQUEST_OPTIONS);
     if ($this->supportsLocalization) {
         $query = $request->getQuery();
         $query->set(Settings::LANG, Settings::$LOCALE);
     }
     return $request;
 }
Exemplo n.º 16
0
 /** @test */
 public function shouldReturnAResponseForARequestObject()
 {
     $mockResponse = $this->createResponse(new Response(200, ['Content-Type' => 'application/json'], Stream::factory(json_encode(['hello' => 'world', 'howareyou' => 'today']))));
     $request = $this->guzzleClient->createRequest('PUT', 'http://example.com/foo', ['query' => ['faz' => 'baz'], 'body' => json_encode(['shakeyo' => 'body']), 'headers' => ['Content-Type' => 'application/json']]);
     $this->httpMock->shouldReceiveRequest($request)->andRespondWith($mockResponse);
     $actualResponse = $this->guzzleClient->put('http://example.com/foo', ['query' => ['faz' => 'baz'], 'body' => json_encode(['shakeyo' => 'body']), 'headers' => ['Content-Type' => 'application/json']]);
     $this->httpMock->verify();
     $this->assertSame($mockResponse, $actualResponse);
 }
Exemplo n.º 17
0
 /**
  * @param string $content
  * @return \GuzzleHttp\Message\Request
  */
 private function buildRequest($content)
 {
     $url = $this->configuration->getUrl();
     $method = $this->configuration->getMethod();
     $request = $this->client->createRequest($method, $url);
     $body = $request->getBody();
     $body->setField('message', $content);
     return $request;
 }
Exemplo n.º 18
0
 /**
  * A simple wrapper for calling any valid service.
  *
  * This function accepts strings so that it is flexible enough to handle
  * new APIs released by CCB without requiring code updates.
  *
  * @param string $httpMethod  Either "GET" or "POST"
  * @param string $serviceName
  * @param array  $args
  *
  * @return SimpleXMLElement
  */
 public function srv($httpMethod, $serviceName, array $args = [])
 {
     $url = "https://{$this->church}.ccbchurch.com/api.php";
     if (!isset($args['query'])) {
         $args['query'] = [];
     }
     $args['query']['srv'] = $serviceName;
     $request = $this->client->createRequest($httpMethod, $url, $args);
     return $this->client->send($request)->xml();
 }
Exemplo n.º 19
0
 /**
  * @param $topic string
  * @param $args array|null
  * @param $kwargs array|null
  * @return array JSON decoded response
  * @throws \Exception
  */
 public function publish($topic, array $args = NULL, array $kwargs = NULL)
 {
     $request = $this->client->createRequest('POST', NULL, array('body' => $this->prepareBody($topic, $args, $kwargs), 'query' => $this->prepareQuery()));
     try {
         $response = $this->client->send($request);
     } catch (\Exception $e) {
         throw $e;
     }
     return $response->json();
 }
 /**
  * Performs a request to the QBank API.
  *
  * @param string $endpoint The API endpoint URL to request.
  * @param array $parameters The parameters to send.
  * @param string $method The HTTP verb to use.
  * @param CachePolicy $cachePolicy The custom caching policy to use.
  * @param bool $delayed If the request should be delayed until destruction.
  *
  * @return array The response result.
  *
  * @throws RequestException
  * @throws ResponseException
  */
 protected function call($endpoint, array $parameters = [], $method = self::METHOD_GET, CachePolicy $cachePolicy = null, $delayed = false)
 {
     $cachePolicy = $cachePolicy !== null ? $cachePolicy : $this->cachePolicy;
     if ($delayed) {
         $this->delayedRequests[] = $this->client->createRequest(strtoupper($method), $endpoint, $parameters);
         $this->logger->debug('Request to QBank added to delayed queue. ' . strtoupper($method) . ' ' . $endpoint, ['endpoint' => $endpoint, 'parameters' => $parameters, 'method' => $method]);
         return [];
     }
     if ($cachePolicy->isEnabled() && ($method == self::METHOD_GET || $method == self::METHOD_POST && preg_match('/v\\d+\\/search/', $endpoint)) && $this->cache->contains(md5($endpoint . json_encode($parameters)))) {
         /** @var string $response */
         $response = $this->cache->fetch(md5($endpoint . json_encode($parameters)));
         $this->logger->info('Using cached response. ' . strtoupper($method) . ' ' . $endpoint, ['endpoint' => $endpoint, 'parameters' => $parameters, 'method' => $method, 'response' => substr(print_r($response, true), 0, 4096)]);
         return $response;
     }
     try {
         $start = microtime(true);
         /** @var ResponseInterface $response */
         $response = $this->client->{$method}($endpoint, $parameters);
         $this->logger->debug('Request to QBank sent. ' . strtoupper($method) . ' ' . $endpoint, ['endpoint' => $endpoint, 'parameters' => $parameters, 'time' => number_format(round((microtime(true) - $start) * 1000), 0, '.', ' ') . ' ms', 'method' => $method, 'response' => substr($response->getBody(), 0, 4096)]);
         $data = null;
         if (in_array('application/json', array_map('trim', explode(';', $response->getHeader('Content-type'))))) {
             try {
                 $data = $response->json();
             } catch (\RuntimeException $re) {
                 $this->logger->error('Error while receiving response from QBank. ' . strtoupper($method) . ' ' . $endpoint, ['message' => 'Response not in json format.', 'endpoint' => $endpoint, 'parameters' => $parameters, 'method' => $method, 'response' => substr($response->getBody(), 0, 4096)]);
                 throw new ResponseException('Error while receiving response from QBank: Response not in json format.');
             }
         } else {
             return $response->getBody()->__toString();
         }
         if ($cachePolicy->isEnabled() && $cachePolicy->getCacheType() == CachePolicy::EVERYTHING && ($method == self::METHOD_GET || $method == self::METHOD_POST && preg_match('/v\\d+\\/search/', $endpoint))) {
             $this->cache->save(md5($endpoint . json_encode($parameters)), $data, $cachePolicy->getLifetime());
         }
         return $data;
     } catch (\GuzzleHttp\Exception\RequestException $re) {
         $this->logger->error('Error while sending request to QBank. ' . strtoupper($method) . ' ' . $endpoint, ['exception' => $re, 'message' => $re->getMessage(), 'endpoint' => $endpoint, 'parameters' => $parameters, 'method' => $method, 'response' => $re->hasResponse() ? substr($re->getResponse()->getBody(), 0, 4096) : '']);
         $message = null;
         $details = null;
         if ($re->hasResponse() && strpos($re->getResponse()->getHeader('content-type'), 'application/json') === 0) {
             $content = $re->getResponse()->json();
             if (!empty($content['error'])) {
                 $details = $content['error'];
             }
             if (isset($content['error']['message'])) {
                 $message = ' [info]' . $content['error']['message'];
             }
             if (isset($content['error']['errors']) && is_array($content['error']['errors'])) {
                 foreach ($content['error']['errors'] as $key => $error) {
                     $message .= "\n\t{$key}: {$error}";
                 }
             }
         }
         throw new RequestException('Error while sending request to QBank: ' . $re->getMessage() . $message, $re->hasResponse() ? $re->getResponse()->getStatusCode() : 0, $re, $details);
     }
 }
Exemplo n.º 21
0
 /**
  * {@inheritdoc}
  */
 public function execute(HttpRequestInterface $request)
 {
     $guzzleRequest = $this->guzzleClient->createRequest($request->getMethod(), $request->getUrl(), ['query' => $request->getParams(), 'headers' => $request->getHeaders()]);
     try {
         $clientResponse = $this->guzzleClient->send($guzzleRequest);
     } catch (RequestException $e) {
         // Re-throw guzzle exception as our own
         throw new HttpTransportException("Guzzle exception", 0, $e);
     }
     return (new HttpResponse())->setBody($clientResponse->getBody())->setHeaders($clientResponse->getHeaders());
 }
 /**
  * @param $topic string
  * @param $args array|null
  * @param $kwargs array|null
  * @return array JSON decoded response
  * @throws \Exception
  */
 public function publish($topic, array $args = null, array $kwargs = null)
 {
     $jsonBody = $this->prepareBody($topic, $args, $kwargs);
     $request = $this->client->createRequest('POST', null, array('body' => $jsonBody, 'query' => $this->prepareSignature($jsonBody)));
     try {
         $response = $this->client->send($request);
     } catch (\Exception $e) {
         throw new PublishRequestException($e->getMessage(), 500, $e);
     }
     return $response->json();
 }
Exemplo n.º 23
0
 public function testCanForeach()
 {
     $c = new Client();
     $requests = [$c->createRequest('GET', 'http://test.com'), $c->createRequest('POST', 'http://test.com'), $c->createRequest('PUT', 'http://test.com')];
     $t = new TransactionIterator(new \ArrayIterator($requests), $c, []);
     $methods = [];
     foreach ($t as $trans) {
         $this->assertInstanceOf('GuzzleHttp\\Adapter\\TransactionInterface', $trans);
         $methods[] = $trans->getRequest()->getMethod();
     }
     $this->assertEquals(['GET', 'POST', 'PUT'], $methods);
 }
 /**
  * @param RequestableInterface $apiRequest
  *
  * @return bool|\GuzzleHttp\Message\ResponseInterface
  */
 public function send(RequestableInterface $apiRequest)
 {
     $request = $this->guzzleClient->createRequest($apiRequest->getMethod(), $apiRequest->getUrl(), $apiRequest->getOptions());
     try {
         return $this->guzzleClient->send($request);
     } catch (ClientException $e) {
         if (null !== $this->logger) {
             $this->logger->alert($e->getMessage());
         }
         return false;
     }
 }
Exemplo n.º 25
0
 /**
  * Wraps HTTP call into a good mould
  *
  * @param  string $method
  * @param  string $endpoint
  * @param  array $data
  * @return Horntell\Http\Response
  * @throws Horntell\Errors\*
  */
 public function send($method, $endpoint, $data = [])
 {
     try {
         $request = $this->client->createRequest($method, $endpoint, ['body' => json_encode($data)]);
         return new Response($this->client->send($request));
     } catch (GuzzleExceptions\RequestException $e) {
         // pass the exception to a helper method,
         // which will figure our what kind of
         // exception to throw
         return $this->handleError($e);
     }
 }
Exemplo n.º 26
0
 protected function newAPIRequest($method, $path, $data = [])
 {
     $api_path = '/api/v1' . $path;
     $client = new GuzzleClient(['base_url' => $this->swapbot_url]);
     $request = $client->createRequest($method, $api_path);
     if ($data and ($method == 'POST' or $method == 'PATCH')) {
         $request = $client->createRequest($method, $api_path, ['json' => $data]);
     } else {
         if ($method == 'GET') {
             $request = $client->createRequest($method, $api_path, ['query' => $data]);
         }
     }
     // add auth
     // $this->getAuthenticationGenerator()->addSignatureToGuzzleRequest($request, $this->api_token, $this->api_secret_key);
     // send request
     try {
         $response = $client->send($request);
     } catch (RequestException $e) {
         if ($response = $e->getResponse()) {
             // interpret the response and error message
             $code = $response->getStatusCode();
             try {
                 $json = $response->json();
             } catch (Exception $parse_json_exception) {
                 // could not parse json
                 $json = null;
             }
             if ($json and isset($json['message'])) {
                 // throw an XChainException with the errorName
                 if (isset($json['errorName'])) {
                     $swapbot_exception = new XChainException($json['message'], $code);
                     $swapbot_exception->setErrorName($json['errorName']);
                     throw $swapbot_exception;
                 }
                 // generic exception
                 throw new Exception($json['message'], $code);
             }
         }
         // if no response, then just throw the original exception
         throw $e;
     }
     $code = $response->getStatusCode();
     if ($code == 204) {
         // empty content
         return [];
     }
     $json = $response->json();
     if (!is_array($json)) {
         throw new Exception("Unexpected response", 1);
     }
     return $json;
 }
Exemplo n.º 27
0
 /**
  * Download new ownCloud package
  * @param Feed $feed
  * @param Callable $onProgress
  * @throws \UnexpectedValueException
  */
 public function getOwncloud(Feed $feed, callable $onProgress)
 {
     if ($feed->isValid()) {
         $downloadPath = $this->getBaseDownloadPath($feed);
         if (!is_writable(dirname($downloadPath))) {
             throw new \Exception(dirname($downloadPath) . ' is not writable.');
         }
         $url = $feed->getUrl();
         $request = $this->httpClient->createRequest('GET', $url, ['save_to' => $downloadPath, 'timeout' => 600]);
         $request->getEmitter()->on('progress', $onProgress);
         $response = $this->httpClient->send($request);
         $this->validateResponse($response);
     }
 }
Exemplo n.º 28
0
 /**
  * Call method
  * @param string $method
  * @param array $data
  * @return mixed
  */
 public function call($method, $data = null)
 {
     $headers = [];
     if ($data) {
         $headers['Content-Type'] = 'multipart/form-data';
     }
     $request = $this->client->createRequest('post', $this->url . $method, ['headers' => [], 'body' => $data]);
     $response = $this->client->send($request);
     $results = $response->json();
     if (!$results['ok']) {
         throw new Exception($results['description'], $results['error_code']);
     }
     return $results['result'];
 }
Exemplo n.º 29
0
 /**
  * Make the request to Premailer
  * @param  array  $params
  * @return \ScottRobertson\Premailer\Response
  */
 private function request(array $params = array())
 {
     $request = $this->client->createRequest('POST', $this->url);
     $body = $request->getBody();
     foreach ($params as $key => $value) {
         $body->setField($key, $value);
     }
     try {
         $response = $this->client->send($request);
     } catch (\Exception $e) {
         throw new \ScottRobertson\Premailer\Exception\Request($e->getMessage());
     }
     return new Response($response->json(), $this->client);
 }
 public function testSendsAllTransactions()
 {
     $client = new Client();
     $requests = [$client->createRequest('GET', 'http://httbin.org'), $client->createRequest('HEAD', 'http://httbin.org')];
     $sent = [];
     $f = new FakeParallelAdapter(new MockAdapter(function ($trans) use(&$sent) {
         $sent[] = $trans->getRequest()->getMethod();
         return new Response(200);
     }));
     $tIter = new TransactionIterator($requests, $client, []);
     $f->sendAll($tIter, 2);
     $this->assertContains('GET', $sent);
     $this->assertContains('HEAD', $sent);
 }