/** * {@inheritdoc} */ public function load(ClassMetadata $metadata, ParserInterface $parser) { // Create a request with basic Auth $request = $this->client->get('repos/' . $this->owner . '/' . $this->repository . '/contents'); try { // Send the request and get the response. $response = $request->send(); } catch (ClientErrorResponseException $e) { $this->handleBadResponseExceptions($e); } $files = $response->json(); $batch = array(); foreach ($files as $file) { $batch[] = $this->client->get('repos/' . $this->owner . '/' . $this->repository . '/contents/' . $file['path']); } try { $responses = $this->client->send($batch); } catch (MultiTransferException $e) { $this->handleBadResponseExceptions($e->getFirst()); } $content = array(); foreach ($responses as $response) { $file = $response->json(); $decodedContent = base64_decode($file['content']); $content[] = $parser->parse($metadata, $file['name'], $decodedContent); } return $content; }
/** * Load remote WSDL to local cache. * * @param string $url * @return string */ public function loadWsdl($url) { $response = $this->guzzleClient->get($url)->send(); $cacheFilePath = $this->getCachedWsdlPath($url); $this->fs->dumpFile($cacheFilePath, $response->getBody(true)); return $cacheFilePath; }
/** * {@inheritdoc} */ public function post($url, array $headers = array(), $content = '') { $headers['content-type'] = 'application/json'; $request = $this->client->post($url, $headers, $content); $this->response = $request->send(); return $this->response->getBody(true); }
/** * {@inheritdoc} */ public function load(ClassMetadata $metadata, ParserInterface $parser) { // Create a request with basic Auth $request = $this->client->get('metadata/dropbox/' . $this->path); try { // Send the request and get the response. $response = $request->send(); } catch (ClientErrorResponseException $e) { $this->handleBadResponseExceptions($e); } $responseBody = $response->json(); $batch = array(); foreach ($responseBody['contents'] as $file) { $batch[] = $this->client->get('https://api-content.dropbox.com/1/files/dropbox' . $file['path']); } try { $responses = $this->client->send($batch); } catch (MultiTransferException $e) { $this->handleBadResponseExceptions($e->getFirst()); } $content = array(); foreach ($responses as $response) { $url = parse_url($response->getEffectiveUrl()); $filename = basename($url['path']); $receivedContent = $response->getBody(true); $content[] = $parser->parse($metadata, $filename, $receivedContent); } return $content; }
/** * Sends the request to given URL and returns JSON response. * * @param string * @return void */ public function handleRequest($url) { $request = $this->client->get($url); $json = ['success' => TRUE, 'error' => NULL, 'body' => NULL]; $this->enableCrossDomainRequests(); try { $result = $request->send(TRUE); } catch (CurlException $e) { $json['success'] = FALSE; $json['error'] = sprintf("Unable to handle request: CURL failed with message '%s'.", $e->getError()); switch ($e->getErrorNo()) { case CURLE_COULDNT_RESOLVE_HOST: http_response_code(404); break; default: http_response_code(400); break; } } if (isset($result)) { $json['body'] = $result->getBody(TRUE); } header('Content-Type: application/json'); echo json_encode($json); }
/** * @param ClientInterface $client * @param LoggerInterface $logger * @param null|string $formatter * @return LogPlugin */ public static function addPsrLoggerToClient(ClientInterface $client, LoggerInterface $logger, $formatter = self::SIMPLE_FORMAT) { $formatter = is_null($formatter) ? self::SIMPLE_FORMAT : $formatter; $adapter = new PsrLogAdapter($logger); $plugin = new LogPlugin($adapter, $formatter); $client->addSubscriber($plugin); return $plugin; }
/** * {@inheritdoc} */ public function getMessage($id) { try { return $this->guzzle->get('/messages/' . $id . '.json')->send()->json(); } catch (GuzzleException $e) { throw new ConnectionException("", 0, $e); } }
/** * {@inheritdoc} */ public function put($url, array $headers = array(), array $content = array(), array $files = array()) { $request = $this->client->put($url, $headers, $content); foreach ($files as $key => $file) { $request->addPostFile($key, $file); } return $this->sendRequest($request); }
/** * Load remote WSDL to local cache. * * @param string $url * @return string */ public function loadWsdl($url) { $clientOptions = ['verify' => empty($this->bundleConfig['sync_settings']['skip_ssl_verification'])]; $response = $this->guzzleClient->get($url, null, $clientOptions)->send(); $cacheFilePath = $this->getCachedWsdlPath($url); $this->fs->dumpFile($cacheFilePath, $response->getBody(true)); return $cacheFilePath; }
public function track($trackingNumber) { try { $response = $this->httpClient->post($this->url, array(), array('API' => 'TrackV2', 'XML' => $this->createTrackRequestXml($trackingNumber)))->send(); } catch (HttpException $e) { throw Exception::createFromHttpException($e); } return $this->parseTrackResponse($response->getBody(true), $trackingNumber); }
public function track($trackingNumber) { try { $response = $this->httpClient->get($this->url, array(), array('query' => array('RQXML' => $this->createRequestXml($trackingNumber))))->send(); } catch (HttpException $e) { throw Exception::createFromHttpException($e); } return $this->parse($response->getBody(true)); }
/** * @param string $endpoint * @param string $content * @param array $headers * @param array $files * * @return Response */ public function send($endpoint, $content, array $headers = array(), array $files = array()) { $request = $this->client->createRequest(RequestInterface::POST, $endpoint, $headers, $content, array('exceptions' => false)); if ($files && $request instanceof EntityEnclosingRequestInterface) { $request->addPostFiles($files); } $response = $request->send(); return new Response($response->getStatusCode(), $response->getBody(true)); }
/** * Factory method which allows for easy service creation * * @param ClientInterface $client * @return self */ public static function factory(ClientInterface $client) { $identity = new self(); if (($client instanceof Base || $client instanceof OpenStack) && $client->hasLogger()) { $identity->setLogger($client->getLogger()); } $identity->setClient($client); $identity->setEndpoint(clone $client->getAuthUrl()); return $identity; }
/** * @param string $access_token * @return User */ public function getByAccessToken($access_token) { $me = $this->http->get('https://graph.facebook.com/me?access_token=' . $access_token)->send()->json(); $data = $this->data_provider->findUserByFacebookId($me['id']); $user = null; if ($data != null) { $user = $this->createUser($data); } return $user; }
/** * Factory method which allows for easy service creation * * @param ClientInterface $client * @return self */ public static function factory(\Guzzle\Http\ClientInterface $client) { $tempAuth = new self(); if (($client instanceof \OpenCloud\Common\Base || $client instanceof \OpenCloud\OpenStack) && $client->hasLogger()) { $tempAuth->setLogger($client->getLogger()); } $tempAuth->setClient($client); $tempAuth->setEndpoint(clone $client->getAuthUrl()); return $tempAuth; }
public function call($wrappedClass, $method, array $params = array()) { $request = $this->client->post(sprintf('/%s/%s', str_replace('\\', '/', $wrappedClass), $method), $params); $auth = $this->getAuthConfig($this->auth); if ($auth) { $request->setAuth($auth['login'], $auth['pass'], $auth['type']); } $response = $request->send(); return $response->getBody(); }
public function track($trackingNumber) { $body = $this->createAuthenticationXml() . $this->createTrackXml($trackingNumber); try { $response = $this->httpClient->post($this->url, array(), $body)->send(); } catch (HttpException $e) { throw Exception::createFromHttpException($e); } return $this->parse($response->getBody(true)); }
/** * * @param \Wehup\AMI\Request\RequestInterface $request * @return \Guzzle\Http\Message\Response */ protected function createHttpRequest(Request\RequestInterface $request) { $httpRequest = $this->httpClient->get('rawman'); $httpRequest->addCookie('mansession_id', $this->cookie); foreach ($request->getParams() as $key => $value) { $httpRequest->getQuery()->set($key, $value); } $httpRequest->getQuery()->set('Action', $request->getAction()); return $httpRequest; }
/** * {@inheritdoc} */ public function post($url, $content = '') { $request = $this->client->post($url, [], $content); try { $this->response = $request->send(); } catch (RequestException $e) { $this->response = $e->getResponse(); $this->handleError(); } return $this->response->getBody(true); }
/** * {@inheritDoc} */ public function format($string) { $request = $this->client->post('markdown', null, json_encode(array('text' => $string))); try { $response = $request->send(); } catch (BadResponseException $e) { $response = $e->getResponse(); $json = $response->json(); throw new RuntimeException(sprintf('Request to Github failed: %s [%d]', $json['message'], $response->getStatusCode())); } return $response->getBody(true); }
protected function setUp() { Phake::initAnnotations($this); Phake::when($this->cryptService)->encryptRSA(Phake::anyParameters())->thenReturn($this->rsaEncrypted); Phake::when($this->cryptService)->sign(Phake::anyParameters())->thenReturn($this->signed); Phake::when($this->cache)->get(GuzzleApiService::CACHE_KEY_PUBLIC_KEY)->thenReturn($this->publicKey); $this->guzzleClient = new Client(); $this->guzzleMockPlugin = new MockPlugin(); $this->guzzleClient->addSubscriber($this->guzzleMockPlugin); $this->apiService = new GuzzleApiService($this->appKey, $this->secretKey, $this->guzzleClient, $this->cryptService, $this->cache, 999999); $this->loggingApiService = new GuzzleApiService($this->appKey, $this->secretKey, $this->guzzleClient, $this->cryptService, $this->cache, 999999, $this->logger); }
/** * Simple factory method for creating services. * * @param Client $client The HTTP client object * @param string $class The class name of the service * @param array $options The options. * @return \OpenCloud\Common\Service\ServiceInterface * @throws ServiceException */ public static function factory(ClientInterface $client, $class, array $options = array()) { $name = isset($options['name']) ? $options['name'] : null; $urlType = isset($options['urlType']) ? $options['urlType'] : null; if (isset($options['region'])) { $region = $options['region']; } elseif ($client->getUser() && ($defaultRegion = $client->getUser()->getDefaultRegion())) { $region = $defaultRegion; } else { $region = null; } return new $class($client, null, $name, $region, $urlType); }
/** * Immediately send all queued requests * * @param bool $async * @return $this */ public function send($async = true) { // Guzzle 3 ignores async; use Guzzle 5 for that. try { $this->client->send($this->queue); } catch (MultiTransferException $exceptions) { foreach ($exceptions as $exception) { // TODO: handle exceptions gracefully throw $exception; } } return $this; }
/** * {@inheritdoc} */ public function generate($toFile = null) { $url = self::BASE_URL; $url .= $this->dimension . '/'; $url .= $this->backgroundColor->getColor(false) . '/'; $url .= $this->stringColor->getColor(false) . '.'; $url .= $this->imageExtension->getExtension() . '&text='; $url .= urlencode($this->text); if ($toFile !== null) { $this->httpClient->get($url)->setResponseBody($toFile)->send(); } return new Result(null, $toFile, $url); }
public function __construct(ClientInterface $client = null) { $this->client = $client; if (!$this->client) { $this->client = new Client(); $this->client->getEventDispatcher()->addListener('request.error', function (Event $event) { // override guzzle default behavior of throwing exceptions // when 4xx & 5xx responses are encountered $event->stopPropagation(); }, -254); $this->client->addSubscriber(BackoffPlugin::getExponentialBackoff(5, array(500, 502, 503, 408))); } }
/** * Get the issues counts from Drupal.org for the specified parameters. * * @param array $commonParameters * An array of query parameters to use in all requests. * @param array $fetchSet * An array to specify separate requests to make and their unique * parameters, in the format * 'setKey' => array( * 'parameterKey' => 'parameterValue', * ) */ public function getCounts($commonParameters, $fetchSet) { $results = array(); foreach ($fetchSet as $fetchKey => $fetchParameters) { $request = $this->client->get('/project/issues/search/drupal'); $request->getQuery()->overwriteWith($commonParameters)->overwriteWith($fetchParameters); try { $results[$fetchKey] = $this->getCount($request); } catch (\Exception $e) { $results[$fetchKey] = null; } } return $results; }
/** * @return Response * @throws ConnectionErrorException * @throws EmptyHostPoolException * @throws ServerErrorException */ public function send() { $exception = null; while ($this->hostPool->hasNext()) { try { $this->guzzleClient->setBaseUrl($this->hostPool->getNext()); /** @var GuzzleRequest $guzzleRequest */ $guzzleRequest = $this->guzzleClient->{$this->method}(array($this->url, $this->binds)); $guzzleRequest->addHeaders($this->headers); if ($this->body && $guzzleRequest instanceof EntityEnclosingRequest) { /** @var EntityEnclosingRequest $guzzleRequest */ $guzzleRequest->setBody($this->body); } $this->updateQueryParams($guzzleRequest); return new Response($guzzleRequest->send()); } catch (ClientErrorResponseException $e) { return new Response($e->getResponse()); } catch (ServerErrorResponseException $e) { $exception = new ServerErrorException(new Response($e->getResponse()), $e->getMessage(), $e->getCode(), $e); } catch (CurlException $e) { $exception = new ConnectionErrorException($e->getMessage(), $e->getCode(), $e); } } if ($exception == null) { throw new EmptyHostPoolException(sprintf("Empty host pool: %s", $this->hostPool->getName())); } throw $exception; }
/** * Execute the url request * * @param string $url * * @return \Guzzle\Http\EntityBodyInterface|string */ protected function request($url) { if (null === $this->httpClient) { $this->httpClient = new HttpClient(); } return $this->httpClient->get($url)->send()->getBody(true); }
public function send() { if (!$this->client) { throw new RuntimeException('A client must be set on the request'); } return $this->client->send($this); }
public function download() { $progressFunctions = null; if ($this->getProgressFunction()) { $progressFunctions = $this->createProgressFunctions(array_fill(0, count($this->requests), 0)); } $requests = array(); foreach ($this->requests as $i => $r) { $requests[] = $request = $this->client->createRequest('GET', $r['url'], array(), null, array('save_to' => $r['file'])); if ($progressFunctions !== null) { // Guzzle progress is too complex for my needs $request->getCurlOptions()->add(CURLOPT_NOPROGRESS, false)->add(CURLOPT_PROGRESSFUNCTION, $progressFunctions[$i]); } } $this->client->send($requests); }