/** * @param string $token * * @return ProviderMetadata */ public function getUserDetails($token) { try { // Fetch user data $response = $this->httpClient->get('https://api.github.com/user', ['Authorization' => sprintf('token %s', $token), 'User-Agent' => 'Pickleweb']); $data = json_decode($response->getContent(), true); if (empty($data) || json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException('Json error'); } // Fetch emails if needed if (empty($data['email'])) { $response = $this->httpClient->get('https://api.github.com/user/emails', ['Authorization' => sprintf('token %s', $token), 'User-Agent' => 'Pickleweb']); $emails = json_decode($response->getContent(), true); if (empty($emails) || json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException('Json error'); } $emails = array_filter($emails, function ($emailData) { return true === $emailData['primary']; }); if (!empty($emails)) { $data['email'] = current($emails)['email']; } } return new ProviderMetadata(['uid' => $data['id'], 'nickName' => $data['login'], 'realName' => $data['name'], 'email' => $data['email'], 'profilePicture' => $data['avatar_url'], 'homepage' => $data['html_url'], 'location' => $data['location']]); } catch (\Exception $e) { throw new \RuntimeException('cannot fetch account details', 0, $e); } }
/** * * @param string $path Path (will be appended to the Base URL) * @param array $params * @param mixed $method * @return \SimpleXMLElement */ protected function request($path, array $params = null, $method = RequestInterface::METHOD_GET) { // Full URL $fullUrl = new Url($this->baseUrl . $path); // Additional headers $headers = array('User-Agent: ' . $this->getUserAgentString()); // Got data? if ($method === RequestInterface::METHOD_GET) { if ($params != null && count($params) > 0) { $fullUrl = new Url($this->baseUrl . $path . '?' . http_build_query($params)); } $response = $this->browser->get($fullUrl, $headers); } else { $response = $this->browser->call($fullUrl, $method, $headers, $params); } // Convert XML $xml = @simplexml_load_string($response->getContent()); // Succesful? if ($xml === false) { throw new MollieException('Server did not respond with valid XML.'); } // Error? if ($xml->item != null && (string) $xml->item['type'] == 'error') { throw new MollieException((string) $xml->item->message, intval($xml->item->errorcode)); } return $xml; }
/** * @param string $token * * @return ProviderMetadata */ public function getUserDetails($token) { try { // Fetch user data list($identifier, $secret) = explode('@', $token); $tokenObject = new TokenCredentials(); $tokenObject->setIdentifier($identifier); $tokenObject->setSecret($secret); $url = 'https://api.bitbucket.org/2.0/user'; $headers = $this->oauthProvider->getHeaders($tokenObject, 'GET', $url); $response = $this->httpClient->get($url, $headers); $data = json_decode($response->getContent(), true); if (empty($data) || json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException('Json error'); } // Fetch email $url = sprintf('https://api.bitbucket.org/1.0/users/%s/emails', $data['username']); $headers = $this->oauthProvider->getHeaders($tokenObject, 'GET', $url); $response = $this->httpClient->get($url, $headers); $emails = json_decode($response->getContent(), true); if (empty($emails) || json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException('Json error'); } $emails = array_filter($emails, function ($emailData) { return true === $emailData['primary']; }); $data['email'] = empty($emails) ? '' : current($emails)['email']; return new ProviderMetadata(['uid' => $data['uuid'], 'nickName' => $data['username'], 'realName' => $data['display_name'], 'email' => $data['email'], 'profilePicture' => $data['links']['avatar']['href'], 'homepage' => $data['links']['html']['href'], 'location' => $data['location']]); } catch (\Exception $e) { throw new \RuntimeException('cannot fetch account details', 0, $e); } }
/** * @param string $sourceLanguage * @param string $destinationLanguage * @param string $text * @return string */ public function translate($sourceLanguage, $destinationLanguage, $text) { $response = $this->browser->get(sprintf(static::API_ENDPOINT_MASK, $sourceLanguage, $destinationLanguage, urlencode($text))); $rawXml = $response->getContent(); $xml = simplexml_load_string($rawXml); return (string) $xml; }
/** * {@inheritdoc} */ public function get($url) { $response = $this->browser->get($url); if (!$response->isSuccessful()) { throw $this->handleResponse($response); } return $response->getContent(); }
/** * @param string $key The key * @param string $pass The pass * @return boolean * @throws BadResponseException */ public function authenticate($key, $pass) { $response = $this->browser->get(sprintf('%s/check/password.json?%s', $this->baseUrl, http_build_query(array('key' => $key, 'pass' => $pass)))); if (500 == $response->getStatusCode()) { throw new BadResponseException($response); } return 'true' == $response->getContent() ? true : false; }
/** * @param string $token * * @return ProviderMetadata */ public function getUserDetails($token) { $data = json_decode($this->httpClient->get('https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' . $token)->getContent(), true); if (empty($data) || json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException('cannot fetch account details'); } return new ProviderMetadata(['uid' => $data['id'], 'nickName' => $data['given_name'], 'realName' => $data['name'], 'email' => $data['email'], 'profilePicture' => $data['picture'], 'homepage' => $data['link']]); }
public function getTickets() { $this->browser->get($this->url . self::TICKET_LIST); $ticketsData = $this->getResponse()->tickets; $tickets = array_map(function ($value) { return new Ticket($value); }, $ticketsData); return $tickets; }
/** * {@inheritDoc} */ public function getContent($url) { try { $response = $this->browser->get($url); $content = $response->getContent(); } catch (\Exception $e) { $content = null; } return $content; }
/** * @throws \InvalidArgumentException * @param $type * @param $url * @param array $headers * @param null $content * @return \Buzz\Message\Response */ private function doRequest($type, $url, $headers = array(), $content = null) { $this->authorize(); $headers = array_merge($headers, array('Authorization: GoogleLogin Auth=' . $this->authToken)); switch ($type) { case 'GET': return $this->httpClient->get($url, $headers); case 'POST': return $this->httpClient->post($url, $headers, $content); default: throw new \InvalidArgumentException($type . ' is no valid request type'); } }
/** * @param $url * @return string * @throws LoadDataException */ public function getResponseContent($url) { try { /** @var \Buzz\Message\Response $buzzResponse */ $buzzResponse = $this->browser->get($url); if (!$buzzResponse->getContent()) { throw new \Exception('Empty response data'); } } catch (\Exception $e) { throw new LoadDataException($e->getMessage(), $e->getCode()); } return $buzzResponse->getContent(); }
/** * {@inheritDoc} * * @throws ConnectionException * @throws UnexpectedResponseException */ public function search($query, $page = null) { $url = $this->getUrl($query, $page); try { $response = $this->browser->get($url); } catch (\Exception $e) { throw new ConnectionException(sprintf('Could not connect to "%s"', $url), 0, $e); } if ($response->getStatusCode() != 200) { throw new UnexpectedResponseException(sprintf('Unexpected response: %s (%d)', $response->getReasonPhrase(), $response->getStatusCode())); } return $this->transformResponse($response->getContent()); }
/** * Get exchange rate * @return float * @throws ProviderUnavailableException * @throws UnsupportedConversionException */ public function doGetExchangeRate() { $url = sprintf($this->baseUrl, $this->baseCurrency, $this->targetCurrency); $response = $this->browser->get($url); if (200 !== $response->getStatusCode()) { throw new ProviderUnavailableException($this->getName()); } $data = explode(',', $response->getContent()); if (!isset($data[1]) || !is_numeric($data[1])) { throw new UnsupportedConversionException($this->baseCurrency, $this->targetCurrency); } return $data[1]; }
/** * @param $latitude * @param $longitude * @return \Manticora\WeatherCenter\Domain\Model\Weather\Weather */ public function findByLocationAndDateTime($latitude, $longitude, DateTimeInterface $dateTime) { $response = $this->client->get('http://api.wunderground.com/api/' . $this->key . '/lang:' . $this->language . '/hourly10day/q/' . $latitude . ',' . $longitude . '.json'); $o = json_decode($response->getContent(), true); $store = new JsonStore($o); $pattern = "\$..hourly_forecast[?(@.FCTTIME.hour == {$dateTime->getHour()}\n && @.FCTTIME.mday == {$dateTime->getDay()}\n && @.FCTTIME.mon == {$dateTime->getMonth()} )]"; $res = $store->get(str_replace(array("\n", "\r"), '', $pattern)); if (!isset($res[0])) { return null; } $weat = $res[0]; $weather = new Weather($weat['condition'], $weat['icon_url'], $weat['temp']['metric'], $weat['humidity'], $weat['pop'], $weat['wspd']['metric'], $weat['wdir']['degrees']); return $weather; }
public function fetchRepository($slug) { $repositoryUrl = sprintf('%s/%s.json', $this->apiUrl, $slug); $buildsUrl = sprintf('%s/%s/builds.json', $this->apiUrl, $slug); $repository = new Repository(); $repositoryArray = json_decode($this->browser->get($repositoryUrl)->getContent(), true); if (!$repositoryArray) { throw new \UnexpectedValueException(sprintf('Response is empty for url %s', $repositoryUrl)); } $repository->fromArray($repositoryArray); $buildCollection = new BuildCollection(json_decode($this->browser->get($buildsUrl)->getContent(), true)); $repository->setBuilds($buildCollection); return $repository; }
/** * @dataProvider fileProvider */ public function testYuml(BuilderInterface $builder, $fixture, $config) { $result = $builder->configure($config)->setPath($fixture)->build(); $this->assertInternalType('array', $result); $this->assertGreaterThan(0, count($result)); $b = new Browser(); foreach ($result as $message) { $url = explode(' ', $message); $response = $b->get($url[1]); $contentType = null; switch ($url[0]) { case '<info>PNG</info>': $contentType = 'image/png'; break; case '<info>PDF</info>': $contentType = 'application/pdf'; break; case '<info>URL</info>': $contentType = 'text/html; charset=utf-8'; break; case '<info>JSON</info>': $contentType = 'application/json'; break; case '<info>SVG</info>': $contentType = 'image/svg+xml'; break; } $this->assertEquals($contentType, $response->getHeader('Content-Type')); } }
/** * @return array */ public function findNearbyLocations(NearbyQuery $query) { $url = self::URL_QUERY . '?' . http_build_query($query->toArray()); // send request $response = $this->browser->get($url); // check for server error if ($response->isServerError()) { throw new \Exception('Server error from fahrplan.sbb.ch: ' . $response->getStatusCode() . ' ' . $response->getReasonPhrase()); } // fix broken JSON $content = $response->getContent(); $content = preg_replace('/(\\w+) ?:/i', '"\\1":', $content); $content = str_replace("\\'", "'", $content); // parse result $result = json_decode($content); // check for JSON error if ($result === null) { throw new \Exception('Invalid JSON from fahrplan.sbb.ch: ' . $content); } $locations = []; foreach ($result->stops as $stop) { $location = Entity\LocationFactory::createFromJson($stop); if ($location) { $location->distance = $location->coordinate->getDistanceTo($query->lat, $query->lon); $locations[] = $location; } } return $locations; }
/** * @Route("/produit/{id}", name="product_plug") * @Template() */ public function plugAction($id) { $browser = new Browser(); $response = $browser->get($this->container->getParameter("back_site") . 'api/products/' . $id); $product = $this->get('jms_serializer')->deserialize($response->getContent(), 'Kali\\Front\\CommandBundle\\Entity\\Product', 'json'); return array('product' => $product, 'site' => $this->container->getParameter("back_site"), 'caracteristics' => $product->getCaracteristics()); }
/** * @Route("/slogan", name="site_slogan") * @Template() */ public function sloganAction() { $browser = new Browser(); $response = $browser->get($this->container->getParameter("back_site") . 'api/parameters'); $paramater = $this->get('jms_serializer')->deserialize($response->getContent(), 'Kali\\Front\\SiteBundle\\Entity\\Parameter', 'json'); return array('slogan' => $paramater->getSlogan(), 'site' => $this->container->getParameter("back_site")); }
/** * Common get request for all API calls * * @param string $resource The path to the resource wanted. For example v2/room * @param array $query Parameters to filter the response for example array('max-results' => 50) * * @return array Decoded array containing response * @throws Exception\RequestException */ public function get($resource, $query = array()) { $url = $this->baseUrl . $resource; if (count($query) > 0) { $url .= "?"; } foreach ($query as $key => $value) { $url .= "{$key}={$value}&"; } $headers = array("Authorization" => $this->auth->getCredential()); $response = $this->browser->get($url, $headers); if ($this->browser->getLastResponse()->getStatusCode() > 299) { throw new RequestException(json_decode($this->browser->getLastResponse()->getContent(), true)); } return json_decode($response->getContent(), true); }
/** * @param integer $page * * @return Crawler */ private function doRequest($page) { $response = $this->browser->get($this->buildUrl($page)); $crawler = new Crawler(); $crawler->add($response->toDomDocument()); return $crawler; }
/** * @Route("/category/list", name="category_list") * @Template() */ public function listAction() { $browser = new Browser(); $response = $browser->get($this->container->getParameter("back_site") . 'api/all/category'); $categories = $this->get('jms_serializer')->deserialize($response->getContent(), 'Doctrine\\Common\\Collections\\ArrayCollection', 'json'); return array("categories" => $categories); }
/** * Calls API through the browser client. * * @param $method * @param $baseUrl * @param array $headers * @param string $content * * @return \Buzz\Message\Response */ protected function call($method, $baseUrl, $headers = array(), $content = '') { if (strtoupper($method) == 'GET') { return $this->browser->get($baseUrl, $headers); } else { return $this->browser->post($baseUrl, $headers, $content); } }
protected function getCrawler() { if (null === $this->crawler) { $client = new Browser(); $this->crawler = new Crawler($client->get($this->url)->getContent()); } return $this->crawler; }
public function it_can_search_with__query(Browser $client, Response $response) { $response->getContent()->shouldBeCalled(); $client->get(sprintf('%s/search?%s', 'http://endpoint', http_build_query(['q' => 'pilkington avenue, birmingham', 'format' => 'json'])), ['User-Agent' => 'Nomatim PHP Library (https://github.com/nixilla/nominatim-consumer); email: not set'])->shouldBeCalled()->willReturn($response); $query = new Query(); $query->setQuery('pilkington avenue, birmingham'); $this->search($query)->shouldReturnAnInstanceOf('Nominatim\\Result\\Collection'); }
public function mention(Request $request) { if ($request->has('code')) { $code = $request->get('code'); $browser = new Browser(new Curl()); $url = "https://web.mention.net/oauth/v2/token"; $response = $browser->post($url, array(), array("client_id" => $this->client_id, "client_secret" => $this->client_secret, "redirect_uri" => $this->callback, "response_type" => "token", "code" => $code, "grant_type" => "authorization_code")); if ($response->getStatusCode() != 200) { return view('404'); } $content = $response->getContent(); $data = json_decode($content); $access_token = $data->access_token; $url = "https://api.mention.net/api/accounts/me"; $response = $browser->get($url, array("Authorization: Bearer {$access_token}", "Accept: application/json")); if (200 != $response->getStatusCode()) { // handle failure } $content = $response->getContent(); $data = json_decode($content); $path = $data->_links->me->href; // fetching account $url = "https://api.mention.net" . $path; $response = $browser->get($url, array("Authorization: Bearer {$access_token}", "Accept: application/json")); if (200 != $response->getStatusCode()) { // handle failure } $content = $response->getContent(); $data = json_decode($content); $account = $data->account; $account_id = $account->id; $url = "https://api.mention.net/api/accounts/{$account_id}/alerts"; $response = $browser->get($url, array("Authorization: Bearer {$access_token}", "Accept: application/json")); if (200 != $response->getStatusCode()) { // handle failure } $content = $response->getContent(); $data = json_decode($content); return view('dropdown')->with('alerts', $data->alerts); } else { $url = "https://web.mention.net/authorize?"; $url .= http_build_query(array("client_id" => $this->client_id, "redirect_uri" => $this->callback, "response_type" => "code")); return redirect($url); } }
public function it_returns_the_correct_historical_object_for_day_data(Browser $browser) { $browser->get($this->baseUrl . '/V?d=3&f=j')->willReturn($this->createResponse($this->dayResponse)); $data = $this->getDataForDay(3); $data->shouldHaveType('Wjzijderveld\\Youless\\Api\\Response\\History'); $data->getValuesInWatt()->shouldBeLike(array(90, 90, 70, 80, 100, 70, 90, 160, 270, 70, 90, 120, 120, 100, 80, 180, 140, 190, 110, 150, 160, 170, 160, 150)); $data->getMeasuredFrom()->shouldBeLike(new DateTime('2014-09-26T00:00:00')); $data->getDeltaInSeconds()->shouldEqual(3600); }
/** * Make request to resource * * @return object Client */ public function makeRequest($path, $params) { $this->dispatcher->dispatch('api.createUri', new GenericEvent($this, array('path' => $path, 'params' => $params))); $this->response = $this->browser->get($this->getUri()); $parsedResponse = json_decode($this->response->getContent(), true); if (array_key_exists('errors', $parsedResponse)) { throw new NewscoopApiException($parsedResponse); } return $this; }
/** * @return string */ public function getObserverVersion() { // version seems to be the same for all servers try { $version = $this->buzz->get($this->getUrl('EUW1') . self::URL_VERSION); } catch (TimeoutException $e) { return false; } return $version->getContent(); }
public function translate($text = '', $to = '', $from = '', $contentType = 'text/plain') { $headers = array($this->authHeader, "Content-Type: text/xml"); $params = http_build_query(compact('text', 'to', 'from', 'contentType')); $request = new Browser(new Curl()); $response = $request->get(static::TRANSLATE_URL . $params, $headers); if ($response->getStatusCode() != 200) { throw new \Exception(strip_tags($response->getContent())); } return strip_tags($response->getContent()); }