/** * {@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; }
/** * Perform a ping request * @return PingResponse * @throws CommunicationError If there was an error communicating with the endpoint * @throws InvalidRequestError If the endpoint proclaims the request invalid */ public function ping() { $request = $this->guzzleClient->get("/v1/ping"); $data = $this->sendRequest($request); $pingResponse = new PingResponse($this->getLaunchKeyDate($data["launchkey_time"]), $data["key"], $this->getLaunchKeyDate($data["date_stamp"])); return $pingResponse; }
/** * {@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); }
/** * {@inheritdoc} */ public function load(ClassMetadata $metadata, ParserInterface $parser, $retries = 0) { try { // Send the request and get the response. $response = $this->client->get('files/' . $this->folder . '/children')->send(); } catch (ClientErrorResponseException $e) { if ($this->client->getDefaultOption('request.options/headers/Authorization') && $retries < 1) { $this->refreshToken(); $retries++; return $this->load($metadata, $parser, $retries); } $this->handleBadResponseExceptions($e); } $json = $response->json(); $files = $json['items']; $batch = array(); foreach ($files as $file) { $batch[] = $this->client->get('files/' . $file['id']); } try { $responses = $this->client->send($batch); } catch (MultiTransferException $e) { $this->handleBadResponseExceptions($e->getFirst()); } $content = array(); foreach ($responses as $response) { $file = $response->json(); $response = $this->client->get($file['downloadUrl'])->send(); $downloadedContent = $response->getBody(true); $content[] = $parser->parse($metadata, $file['originalFilename'], $downloadedContent); } 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 getMessage($id) { try { return $this->guzzle->get('/messages/' . $id . '.json')->send()->json(); } catch (GuzzleException $e) { throw new ConnectionException("", 0, $e); } }
/** * 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->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)); }
/** * {@inheritdoc} */ public function get($url) { try { $this->response = $this->client->get($url)->send(); } catch (RequestException $e) { $this->response = $e->getResponse(); $this->handleError(); } return $this->response->getBody(true); }
/** * @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; }
/** * * @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 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); }
/** * 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; }
/** * 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); }
/** * @param array $postData * @return \Guzzle\Http\Message\EntityEnclosingRequestInterface|\Guzzle\Http\Message\RequestInterface * @throws Exceptions\BadServiceException * @throws Exceptions\AppNexusAPIException */ private function buildRequestObject(array $postData = array()) { $where = $this->where; if (isset($where['since'])) { if (!$this->getServiceObject($this->getService())->supportsSince()) { throw new BadServiceException(sprintf("[%s] does not support `since()`", $this->getService())); } switch ($this->getService()) { case self::SERVICE_LANGUAGE: $key = 'min_last_activity'; break; default: $key = 'min_last_modified'; break; } $where[$key] = $where['since']; unset($where['since']); } $uri = sprintf("/%s?%s", $this->getService(), http_build_query($where)); switch ($this->getServiceObject($this->getService())->getRequestVerb()) { case 'get': return $this->client->get($uri, array('Authorization' => $this->token)); break; case 'post': return $this->client->post($uri, array('Authorization' => $this->token), json_encode($postData)); break; default: throw new AppNexusAPIException(sprintf("Unknown verb [%s]", $this->getServiceObject($this->getService())->getRequestVerb())); } }
/** * Perform a cURL request based on a supplied path * * @param string $path * * @return array */ private function call($path) { $this->client->setBaseUrl(self::URL); $request = $this->client->get($path); $request->setHeader('Accept', 'application/json'); return $request->send()->json(); }
/** * Perform an HTTP request on MusicBrainz * * @param string $path * @param array $params * @param string $options * @param boolean $isAuthRequred * @return array */ public function call($path, array $params = array(), array $options = array(), $isAuthRequred = false) { if ($options['user-agent'] == '') { throw new Exception('You must set a valid User Agent before accessing the MusicBrainz API'); } $this->client->setBaseUrl(MbClient::URL); $this->client->setConfig(array('data' => $params)); $request = $this->client->get($path . '{?data*}'); $request->setHeader('Accept', 'application/json'); $request->setHeader('User-Agent', $options['user-agent']); if ($isAuthRequred) { if ($options['user'] != null && $options['password'] != null) { $request->setAuth($options['user'], $options['password'], CURLAUTH_DIGEST); } else { throw new Exception('Authentication is required'); } } $request->getQuery()->useUrlEncoding(false); return $request->send()->json(); }
/** * Get a single playlist by ID * * @param int $playlistId * @param array $embeds List of embed strings (such as content.system_data) detailing additional * data to return with the result set * * @return array */ public function getPlaylistById($playlistId, array $embeds = array()) { $this->validatePlaylistEmbeds($embeds); $params = $this->baseParams + array('embed' => implode(',', $embeds), 'playlist_id' => $playlistId); $params['signature'] = $this->generateSignature($params); unset($params['playlist_id']); $params = array_filter($params); $query = $this->buildQueryString($params); $request = $this->httpClient->get('playlists/' . $playlistId . $query); $response = $request->send(); return $response->json(); }
/** * {@inheritdoc} */ public function load(ClassMetadata $metadata, ParserInterface $parser) { $content = array(); $tempFile = tmpfile(); $response = $this->client->get($this->url, null, $tempFile)->send(); $zipFile = $response->getBody()->getUri(); $zip = zip_open($zipFile); if (!is_resource($zip)) { throw new RuntimeException(sprintf('Something went wrong when opening %s.', $zipFile)); } while ($zipEntry = zip_read($zip)) { $fileName = zip_entry_name($zipEntry); $fileSize = zip_entry_filesize($zipEntry); $fileContent = zip_entry_read($zipEntry, $fileSize); if ($fileContent) { $content[] = $parser->parse($metadata, basename($fileName), $fileContent); } } zip_close($zip); return $content; }
/** * GET request * * @param string $path The path to query * @param array $args An array of query parameters * @return string The response body * @throws BadResponseException * @throws RuntimeException */ public function get($path, array $args = array()) { $queryDatas = $this->formatQueryParameters($args); $path = sprintf('%s%s', ltrim($path, '/'), $this->getTemplate($queryDatas['data'])); try { $request = $this->client->get(array($path, $queryDatas)); $request->setHeader('Accept', 'application/json'); $this->log($request->getRawHeaders()); $response = $request->send(); $this->log($response->getRawHeaders()); } catch (CurlException $e) { throw new RuntimeException($e->getMessage(), $e->getErrorNo(), $e); } catch (GuzzleBadResponse $e) { $response = $e->getResponse(); $ex = new BadResponseException($response->getReasonPhrase(), $e->getCode(), $e); $ex->setResponseBody($response->getBody())->setHttpStatusCode($response->getStatusCode()); throw $ex; } catch (GuzzleException $e) { throw new RuntimeException($e->getMessage(), $e->getCode(), $e); } return $response->getBody(); }
function it_build_a_get_request(ClientInterface $client, RequestInterface $request) { $client->get('/resource?foo=bar&baz=foo', ['some headers'], ['some options'])->shouldBeCalled(1)->willReturn($request); $this->setClient($client); $this->build('/resource', ['foo' => 'bar', 'baz' => 'foo'], ['some headers'], null, null, ['some options'])->shouldReturn($request); }
/** * {@inheritdoc} */ public function getContent($url, array $headers = array()) { return $this->sendRequest($this->client->get($url, $headers)); }
/** * {@inheritdoc} */ public function get($url) { $this->response = $this->client->get($url)->send(); return $this->response->getBody(true); }
/** * @param $gtin * @return Barcode */ public function lookup($gtin) { $data = $this->client->get('/barcode/' . $gtin)->send()->json(); return new Barcode($data['uuid'], $data['gtin']); }
/** * Execute the request to get the access token. * * @param Guzzle\Http\ClientInterface $client * @param array $options * @return Guzzle\Http\Message\Response */ protected function executeAccessRequest(ClientInterface $client, $options) { $url = $this->getAccessEndpoint() . '?' . http_build_query($options); return $client->get($url)->send(); }
/** * @throws InvalidArgumentException When any of the options "company", "collection" are not provided */ private function doRequest(array $pathParts, $data = array()) { $this->lastErrors = array(); if (!isset($data['company'])) { $data['company'] = $this->companyName; } if (!isset($data['collection'])) { $data['collection'] = $this->collectionName; } foreach (array('company', 'collection') as $key) { if (!isset($data[$key])) { throw new InvalidArgumentException(sprintf('The option "%s" must be provided.', $key)); } } if (isset($data['cols'])) { $data['cols'] = $this->encodeColumns($data['meta']); } if (isset($data['scales'])) { $data['scales'] = $this->encodeScales($data['scales']); } if (isset($opts['filters'])) { $data['filters'] = $this->encodeFilters($data['filters']); } $url = sprintf('%s/%s', $this->pathPrefix, implode('/', $pathParts)); if (isset($data['models']) && count($data['models'])) { $url = sprintf('%s/%s', $url, $this->encodeModels($data['models'])); } $useGET = !count($data); if (isset($data['_method']) && $data['_method'] === 'GET') { $useGET = true; unset($data['_method']); } if ($useGET) { $request = $this->httpClient->get($url); $query = $request->getQuery(); $query->merge($data); } else { $request = $this->httpClient->post($url); if (count($data)) { $request->addPostFields($data); } if (isset($data['inputfile']) && $data['inputfile']) { $inputFile = $data['inputfile']; $mimeType = MimeTypeGuesser::getInstance()->guess($inputFile); $request->addPostFile('inputfile', $inputFile, $mimeType); } } $request->setPort($this->port); if ($this->accessKey && $this->secretKey) { $request->setAuth($this->accessKey, $this->secretKey); } if (null !== $this->logger) { $this->logger->debug(sprintf('Sending request to Sajari engine: %s', $request)); } $response = $request->send(); if (null !== $this->logger) { $this->logger->debug(sprintf('Received response from Sajari engine: %s', $response->getBody(true))); } $this->lastRawResponse = $response->getBody(true); $jsonResponse = $response->json(); $this->lastResponse = $response; if (!$jsonResponse) { $this->lastErrors[] = 'No response'; return false; } $statusCode = (int) $jsonResponse['statusCode']; if ($statusCode === 200) { $result = true; if (isset($jsonResponse['response'])) { $result = $jsonResponse['response']; if (isset($jsonResponse['msecs'])) { $result['msecs'] = $jsonResponse['msecs']; } } return $result; } $errors = isset($jsonResponse['errors']) ? $jsonResponse['errors'] : array('Unknown error'); $this->lastErrors = array_merge($this->lastErrors, $errors); return false; }
/** * @return \Guzzle\Http\Message\RequestInterface */ private function buildRequest() { return $this->client->get($this->resource->getOriginal()); }
/** * {@inheritDoc} */ public function get($path, array $parameters = array(), array $headers = array()) { $parameters = $this->buildQueryParameters($parameters); return $this->request($this->client->get($path, $headers, $parameters)); }
/** * {@inheritdoc} */ public function getTranslation($masterfile, $lang) { $url = $this->getApiUrl('translation', array('master-file-name' => $masterfile, 'language-tag' => $lang)); $response = $this->httpClient->get($url)->send(); return $response->getBody(true); }