/**
  * Make a Http Request
  * @param       string          $method         The Http verb
  * @param       string          $url            The relative URL after the host name
  * @param       array|null      $apiRequest     Contents of the body
  * @param       array|null      $queryString    Data to add as a queryString to the url
  * @return      mixed
  * @throws      RequiredFieldMissingException
  * @throws      ConnectException
  * @throws      RequestException
  * @throws      \Exception
  */
 public function makeHttpRequest($method, $url, $apiRequest = null, $queryString = null)
 {
     $this->apiConfiguration->validate();
     $urlEndPoint = $this->apiConfiguration->getApiEndPoint() . '/' . $url;
     $data = ['headers' => ['Authorization' => 'Bearer ' . $this->apiConfiguration->getAccessToken()], 'json' => $apiRequest, 'query' => $queryString];
     try {
         switch ($method) {
             case 'post':
                 $response = $this->guzzle->post($urlEndPoint, $data);
                 break;
             case 'put':
                 $response = $this->guzzle->put($urlEndPoint, $data);
                 break;
             case 'delete':
                 $response = $this->guzzle->delete($urlEndPoint, $data);
                 break;
             case 'get':
                 $response = $this->guzzle->get($urlEndPoint, $data);
                 break;
             default:
                 throw new \Exception('Missing request method');
         }
         if (in_array(current($response->getHeader('Content-Type')), ['image/png', 'image/jpg'])) {
             $result = $response->getBody()->getContents();
         } else {
             $result = json_decode($response->getBody(), true);
         }
         return $result;
     } catch (ConnectException $c) {
         throw $c;
     } catch (RequestException $e) {
         throw $e;
     }
 }
Example #2
1
 public function getAllProjects()
 {
     $key = "{$this->cachePrefix}-all-projects";
     if ($this->cache && ($projects = $this->cache->fetch($key))) {
         return $projects;
     }
     $first = json_decode($this->client->get('projects.json', ['query' => ['limit' => 100]])->getBody(), true);
     $projects = $first['projects'];
     if ($first['total_count'] > 100) {
         $requests = [];
         for ($i = 100; $i < $first['total_count']; $i += 100) {
             $requests[] = $this->client->getAsync('projects.json', ['query' => ['limit' => 100, 'offset' => $i]]);
         }
         /** @var Response[] $responses */
         $responses = Promise\unwrap($requests);
         $responseProjects = array_map(function (Response $response) {
             return json_decode($response->getBody(), true)['projects'];
         }, $responses);
         $responseProjects[] = $projects;
         $projects = call_user_func_array('array_merge', $responseProjects);
     }
     usort($projects, function ($projectA, $projectB) {
         return strcasecmp($projectA['name'], $projectB['name']);
     });
     $this->cache && $this->cache->save($key, $projects);
     return $projects;
 }
Example #3
0
 /**
  * Execute the console command.
  * @return mixed
  */
 public function handle()
 {
     $client = new Client();
     //Call to EMS API to get the employee details
     $date = Carbon::yesterday()->format('Y-m-d');
     //$date = '2016-03-03';
     $ems_data = $client->get(env(APP_HOST) . "/" . EMS_API_PATH . 'employee_list/' . $date);
     if ($ems_data->getStatusCode() == STATUS_OK) {
         $data = json_decode($ems_data->getBody()->getContents());
         foreach ($data as $key => $ems) {
             $staff = Staff::whereEmail($ems->employee_email_id)->first();
             if (!empty($staff)) {
                 //Find JIRA hours
                 $worklog = Timelog::whereStaffId($staff->id)->whereStarted($date)->sum('time_spent');
                 $actual_jira_hours = gmdate('H:i:s', $worklog);
                 $actual_ems_hours = $ems->actual_hours;
                 //Comparing EMS and JIRA hours
                 if ($actual_jira_hours != NULL && $actual_jira_hours != '00:00:00' && $actual_ems_hours != NULL && $actual_ems_hours != '00:00:00') {
                     $diffrence = $actual_ems_hours - $actual_jira_hours;
                     //IF difference is greater then 1 hour, then update EMS
                     // Call back to EMS to mark employee as half absent
                     $client->get(env(APP_HOST) . "/" . EMS_API_PATH . 'update_employee_timesheet/' . $ems->emp_id . '/' . $date . ($diffrence > ONE && $diffrence < FOUR) ? '/half' : '/full');
                 }
             }
         }
     }
 }
 /**
  * @param string $url
  * @return mixed
  */
 protected function get($url)
 {
     /** @noinspection PhpVoidFunctionResultUsedInspection */
     /** @var Response $response */
     $response = $this->client->get($url);
     return json_decode($response->getBody());
 }
Example #5
0
 /**
  * Validate the service ticket parameter present in the request.
  *
  * This method will return the username of the user if valid, and raise an
  * exception if the ticket is not found or not valid.
  *
  * @param string $version
  *   The protocol version of the CAS server.
  * @param string $ticket
  *   The CAS authentication ticket to validate.
  * @param array $service_params
  *   An array of query string parameters to add to the service URL.
  *
  * @return array
  *   An array containing validation result data from the CAS server.
  * @throws CasValidateException
  */
 public function validateTicket($version, $ticket, $service_params = array())
 {
     try {
         $validate_url = $this->casHelper->getServerValidateUrl($ticket, $service_params);
         $this->casHelper->log("Trying to validate against {$validate_url}");
         $options = array();
         $cert = $this->casHelper->getCertificateAuthorityPem();
         if (!empty($cert)) {
             $options['verify'] = $cert;
         } else {
             $options['verify'] = FALSE;
         }
         $response = $this->httpClient->get($validate_url, $options);
         $response_data = $response->getBody()->__toString();
         $this->casHelper->log("Received " . htmlspecialchars($response_data));
     } catch (ClientException $e) {
         throw new CasValidateException("Error with request to validate ticket: " . $e->getMessage());
     }
     switch ($version) {
         case "1.0":
             return $this->validateVersion1($response_data);
         case "2.0":
             return $this->validateVersion2($response_data);
     }
     // If we get here, its because we had a bad CAS version specified.
     throw new CasValidateException("Unknown CAS protocol version specified.");
 }
 /**
  * @param string $url
  * @param string $saveTo
  */
 private function downloadFile($url, $saveTo)
 {
     if ($this->progressBar) {
         $this->setDownloadWithProgressBar();
     }
     $this->httpClient->get($url, ['save_to' => $saveTo]);
 }
Example #7
0
 /**
  * Validate the service ticket parameter present in the request.
  *
  * This method will return the username of the user if valid, and raise an
  * exception if the ticket is not found or not valid.
  *
  * @param string $ticket
  *   The CAS authentication ticket to validate.
  * @param array $service_params
  *   An array of query string parameters to add to the service URL.
  *
  * @return array
  *   An array containing validation result data from the CAS server.
  *
  * @throws CasValidateException
  *   Thrown if there was a problem making the validation request or
  *   if there was a local configuration issue.
  */
 public function validateTicket($ticket, $service_params = array())
 {
     $options = array();
     $verify = $this->casHelper->getSslVerificationMethod();
     switch ($verify) {
         case CasHelper::CA_CUSTOM:
             $cert = $this->casHelper->getCertificateAuthorityPem();
             $options['verify'] = $cert;
             break;
         case CasHelper::CA_NONE:
             $options['verify'] = FALSE;
             break;
         case CasHelper::CA_DEFAULT:
         default:
             // This triggers for CasHelper::CA_DEFAULT.
             $options['verify'] = TRUE;
     }
     $validate_url = $this->casHelper->getServerValidateUrl($ticket, $service_params);
     $this->casHelper->log("Attempting to validate service ticket using URL {$validate_url}");
     try {
         $response = $this->httpClient->get($validate_url, $options);
         $response_data = $response->getBody()->__toString();
         $this->casHelper->log("Validation response received from CAS server: " . htmlspecialchars($response_data));
     } catch (RequestException $e) {
         throw new CasValidateException("Error with request to validate ticket: " . $e->getMessage());
     }
     $protocol_version = $this->casHelper->getCasProtocolVersion();
     switch ($protocol_version) {
         case "1.0":
             return $this->validateVersion1($response_data);
         case "2.0":
             return $this->validateVersion2($response_data);
     }
     throw new CasValidateException('Unknown CAS protocol version specified: ' . $protocol_version);
 }
Example #8
0
 /**
  * Execute the get method on the guzzle client and create a response
  *
  * @param array $opts
  * @return Response
  */
 public function call(array $opts, $url)
 {
     /** @var ResponseInterface $response */
     /** @noinspection PhpVoidFunctionResultUsedInspection */
     $response = $this->client->get($url, $opts);
     return new Response($response);
 }
 /**
  * Login with Facebook.
  *
  * @param Request $request
  * @return \Illuminate\Http\JsonResponse
  */
 public function facebook(Request $request)
 {
     $accessTokenUrl = 'https://graph.facebook.com/v2.5/oauth/access_token';
     $graphApiUrl = 'https://graph.facebook.com/v2.5/me';
     $params = ['code' => $request->input('code'), 'client_id' => $request->input('clientId'), 'redirect_uri' => $request->input('redirectUri'), 'client_secret' => Config::get('app.facebook_secret')];
     $client = new GuzzleHttp\Client();
     // Step 1. Exchange authorization code for access token.
     $accessToken = json_decode($client->get($accessTokenUrl, ['query' => $params])->getBody(), true);
     // Step 2. Retrieve profile information about the current user.
     $profile = json_decode($client->get($graphApiUrl, ['query' => $accessToken])->getBody(), true);
     // Step 3a. If user is already signed in then link accounts.
     if ($request->header('Authorization')) {
         $user = User::where('facebook', '=', $profile['id']);
         $userData = $user->first();
         if ($userData) {
             return response()->json(['token' => $this->createToken($userData)]);
         }
         $token = explode(' ', $request->header('Authorization'))[1];
         $payload = json_decode(Crypt::decrypt($token));
         $user = User::find($payload['sub']);
         $user->facebook = $profile['id'];
         $user->displayName = $user->displayName ?: $profile['name'];
         $user->save();
         return response()->json(['token' => $this->createToken($user)]);
     } else {
         $user = User::where('facebook', '=', $profile['id']);
         if ($user->first()) {
             return response()->json(['token' => $this->createToken($user->first())]);
         }
         $user = new User();
         $user->facebook = $profile['id'];
         $user->save();
         return response()->json(['token' => $this->createToken($user)]);
     }
 }
 /**
  * Execute the command.
  *
  * @param InputInterface $input The input.
  * @param OutputInterface $output The output.
  * @throws InvalidArgumentException If the configuration is not specified.
  * @return integer
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $configFile = $input->getOption('config-file');
     $config = Yaml::parse(file_get_contents($configFile), true);
     if (!isset($config['strava']['auth'])) {
         throw new InvalidArgumentException('There is no configuration specified for tracker "strava". See example config.');
     }
     $secretToken = $config['strava']['auth']['secretToken'];
     $clientID = $config['strava']['auth']['clientID'];
     $username = $config['strava']['auth']['username'];
     $password = $config['strava']['auth']['password'];
     $httpClient = new Client();
     /** @var \GuzzleHttp\Message\ResponseInterface $response */
     // Do normal login.
     $response = $httpClient->get('https://www.strava.com/login', ['cookies' => true]);
     $authenticityToken = $this->getAuthenticityToken($response);
     // Perform the login to strava.com
     $httpClient->post('https://www.strava.com/session', array('cookies' => true, 'body' => array('authenticity_token' => $authenticityToken, 'email' => $username, 'password' => $password)));
     // Get the authorize page.
     $response = $httpClient->get('https://www.strava.com/oauth/authorize?client_id=' . $clientID . '&response_type=code&redirect_uri=http://localhost&scope=view_private,write&approval_prompt=force', ['cookies' => true]);
     $authenticityToken = $this->getAuthenticityToken($response);
     // Accept the application.
     $response = $httpClient->post('https://www.strava.com/oauth/accept_application?client_id=' . $clientID . '&response_type=code&redirect_uri=http://localhost&scope=view_private,write', array('cookies' => true, 'allow_redirects' => false, 'body' => array('authenticity_token' => $authenticityToken)));
     $redirectLocation = $response->getHeader('Location');
     $urlQuery = parse_url($redirectLocation, PHP_URL_QUERY);
     parse_str($urlQuery, $urlQuery);
     $authorizationCode = $urlQuery['code'];
     // Token exchange.
     $response = $httpClient->post('https://www.strava.com/oauth/token', array('body' => array('client_id' => $clientID, 'client_secret' => $secretToken, 'code' => $authorizationCode)));
     $jsonResponse = $response->json();
     $code = $jsonResponse['access_token'];
     $output->writeln('Your access token is: <comment>' . $code . '</comment>');
     return 0;
 }
    /**
     * @test
     */
    public function histogramsShouldIncrementAtomically()
    {
        $start = microtime(true);
        $promises = [$this->client->getAsync('/examples/some_histogram.php?c=0&adapter=' . $this->adapter), $this->client->getAsync('/examples/some_histogram.php?c=1&adapter=' . $this->adapter), $this->client->getAsync('/examples/some_histogram.php?c=2&adapter=' . $this->adapter), $this->client->getAsync('/examples/some_histogram.php?c=3&adapter=' . $this->adapter), $this->client->getAsync('/examples/some_histogram.php?c=4&adapter=' . $this->adapter), $this->client->getAsync('/examples/some_histogram.php?c=5&adapter=' . $this->adapter), $this->client->getAsync('/examples/some_histogram.php?c=6&adapter=' . $this->adapter), $this->client->getAsync('/examples/some_histogram.php?c=7&adapter=' . $this->adapter), $this->client->getAsync('/examples/some_histogram.php?c=8&adapter=' . $this->adapter), $this->client->getAsync('/examples/some_histogram.php?c=9&adapter=' . $this->adapter)];
        Promise\settle($promises)->wait();
        $end = microtime(true);
        echo "\ntime: " . ($end - $start) . "\n";
        $metricsResult = $this->client->get('/examples/metrics.php?adapter=' . $this->adapter);
        $body = (string) $metricsResult->getBody();
        $this->assertThat($body, $this->stringContains(<<<EOF
test_some_histogram_bucket{type="blue",le="0.1"} 1
test_some_histogram_bucket{type="blue",le="1"} 2
test_some_histogram_bucket{type="blue",le="2"} 3
test_some_histogram_bucket{type="blue",le="3.5"} 4
test_some_histogram_bucket{type="blue",le="4"} 5
test_some_histogram_bucket{type="blue",le="5"} 6
test_some_histogram_bucket{type="blue",le="6"} 7
test_some_histogram_bucket{type="blue",le="7"} 8
test_some_histogram_bucket{type="blue",le="8"} 9
test_some_histogram_bucket{type="blue",le="9"} 10
test_some_histogram_bucket{type="blue",le="+Inf"} 10
test_some_histogram_count{type="blue"} 10
test_some_histogram_sum{type="blue"} 45
EOF
));
    }
Example #12
0
 public function fire()
 {
     $client = new Client(array('base_uri' => 'https://hacker-news.firebaseio.com'));
     $endpoints = array('top' => '/v0/topstories.json', 'ask' => '/v0/askstories.json', 'job' => '/v0/jobstories.json', 'show' => '/v0/showstories.json', 'new' => '/v0/newstories.json');
     foreach ($endpoints as $type => $endpoint) {
         $response = $client->get($endpoint);
         $result = $response->getBody();
         $items = json_decode($result, true);
         foreach ($items as $id) {
             $item_res = $client->get("/v0/item/" . $id . ".json");
             $item_data = json_decode($item_res->getBody(), true);
             if (!empty($item_data)) {
                 $item = array('id' => $id, 'title' => $item_data['title'], 'item_type' => $item_data['type'], 'username' => $item_data['by'], 'score' => $item_data['score'], 'time_stamp' => $item_data['time']);
                 $item['is_' . $type] = true;
                 if (!empty($item_data['text'])) {
                     $item['description'] = strip_tags($item_data['text']);
                 }
                 if (!empty($item_data['url'])) {
                     $item['url'] = $item_data['url'];
                 }
                 $db_item = DB::table('items')->where('id', '=', $id)->first();
                 if (empty($db_item)) {
                     DB::table('items')->insert($item);
                 } else {
                     DB::table('items')->where('id', $id)->update($item);
                 }
             }
         }
     }
     return 'ok';
 }
Example #13
0
 /**
  * Perform the check of a URL
  *
  * @param string $url URL to check
  * @param int $timeout timeout for the request. Defaults to 5 seconds
  * @return Status
  */
 public function check($url, $timeout = 5)
 {
     $this->validateUrl($url);
     $response = null;
     $statusCode = null;
     $reason = null;
     $unresolved = false;
     $timeStart = microtime(true);
     try {
         $response = $this->guzzle->get($url, ['timeout' => $timeout]);
         $statusCode = $response->getStatusCode();
     } catch (ClientException $e) {
         // When not a 200 status but still responding
         $statusCode = $e->getCode();
         $reason = $e->getMessage();
     } catch (ConnectException $e) {
         // Unresolvable host etc
         $reason = $e->getMessage();
         $unresolved = true;
     } catch (\Exception $e) {
         // Other errors
         $reason = $e->getMessage();
         $unresolved = true;
     }
     $timeEnd = microtime(true);
     $time = $timeEnd - $timeStart;
     // seconds
     return new UrlStatus($url, $statusCode, $time, $unresolved, $response, $reason);
 }
Example #14
0
 /**
  * @return MailTesterMessage
  */
 public function getLastEmail()
 {
     $inboxId = $this->config['inbox_id'];
     $messageId = $this->getAllEmails()[0]['id'];
     $email = $this->mailtrap->get("/api/v1/inboxes/{$inboxId}/messages/{$messageId}")->json();
     return $this->populateMessage($messageId, $email);
 }
Example #15
0
 /**
  * @param string $url
  * @param array $options
  * @throws GuzzleException
  * @return Response
  */
 public function get($url, array $options = [])
 {
     if (strpos($url, 'http') !== 0) {
         $url = $this->baseUrl . '/' . $this->collection . '/' . ltrim($url, '/');
     }
     return new Response($this, $this->client->get($url, $options));
 }
Example #16
0
 /**
  * Execute the command.
  *
  * @param  \Symfony\Component\Console\Input\InputInterface  $input
  * @param  \Symfony\Component\Console\Output\OutputInterface  $output
  * @return void
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $client = new Client();
     $modname = $input->getArgument('modname');
     $modversion = $input->getArgument('modversion');
     $config = solder_config();
     $response = $client->get($config->api);
     $server = $response->json();
     $response = $client->get($config->api . '/mod/' . $modname . '/' . $modversion);
     $json = $response->json();
     if (isset($json['error'])) {
         throw new \Exception($json['error']);
     }
     $rows = array();
     foreach ($json as $key => $value) {
         if ($key == 'versions') {
             $rows[] = array("<info>{$key}</info>", implode($value, "\n"));
         } else {
             $rows[] = array("<info>{$key}</info>", mb_strimwidth($value, 0, 80, "..."));
         }
     }
     $output->writeln('<comment>Server:</comment>');
     $output->writeln(" <info>{$server['api']}</info> version {$server['version']}");
     $output->writeln(" {$api}");
     $output->writeln('');
     $output->writeln("<comment>Mod:</comment>");
     $table = new Table($output);
     $table->setRows($rows)->setStyle('compact')->render();
 }
 public function run()
 {
     if (Yii::$app->getRequest()->isPost) {
         Yii::$app->getRequest()->parsers = ['application/json' => 'yii\\web\\JsonParser'];
         $user_class = Satellizer::getComponent()->identityClass;
         $params = ['code' => Yii::$app->getRequest()->getBodyParam('code'), 'client_id' => Yii::$app->getRequest()->getBodyParam('clientId'), 'redirect_uri' => Yii::$app->getRequest()->getBodyParam('redirectUri'), 'client_secret' => Satellizer::getComponent()->facebook['clientSecret']];
         $cliente = new Client();
         $accessToken = $cliente->get(Satellizer::getComponent()->facebook['accessTokenUrl'], ['query' => $params])->json();
         $profile = $cliente->get(Satellizer::getComponent()->facebook['graphApiUrl'], ['query' => $accessToken])->json();
         if (Yii::$app->getRequest()->getHeaders()->get('Authorization')) {
             $user = $user_class::findOne(['facebook' => $profile['id']]);
             if ($user) {
                 throw new \yii\web\ConflictHttpException('There is already a Facebook account that belongs to you', 409);
             }
             $token = explode(' ', Yii::$app->getRequest()->getHeaders()->getHeaders()->get('Authorization'))[1];
             $payload = (array) Satellizer::getComponent()->decodeToken($token);
             $user = $user_class::find($payload['sub']);
             $this->facebook = $profile['id'];
             $user->save();
             $user->facebookLink($profile);
         } else {
             $user = $user_class::findOne(['facebook' => $profile['id']]);
             if ($user) {
                 return ['token' => Satellizer::getComponent()->createToken($user)];
             }
             $user = Yii::createObject($user_class);
             $this->facebook = $profile['id'];
             $user->save();
             $user->facebookLink($profile);
         }
         return ['token' => Satellizer::getComponent()->createToken($user)];
     }
 }
 /**
  * Get the list of videos from YouTube
  *
  * @param string $channelId
  * @throws \Mcfedr\YouTube\LiveStreamsBundle\Exception\MissingChannelIdException
  * @return array
  */
 public function getStreams($channelId = null)
 {
     if (!$channelId) {
         $channelId = $this->channelId;
     }
     if (!$channelId) {
         throw new MissingChannelIdException("You must specify the channel id");
     }
     if ($this->cache) {
         $data = $this->cache->fetch($this->getCacheKey($channelId));
         if ($data !== false) {
             return $data;
         }
     }
     $searchResponse = $this->client->get('search', ['query' => ['part' => 'id', 'channelId' => $channelId, 'eventType' => 'live', 'type' => 'video', 'maxResults' => 50]]);
     $searchData = json_decode($searchResponse->getBody()->getContents(), true);
     $videosResponse = $this->client->get('videos', ['query' => ['part' => 'id,snippet,liveStreamingDetails', 'id' => implode(',', array_map(function ($video) {
         return $video['id']['videoId'];
     }, $searchData['items']))]]);
     $videosData = json_decode($videosResponse->getBody()->getContents(), true);
     $streams = array_map(function ($video) {
         return ['name' => $video['snippet']['title'], 'thumb' => $video['snippet']['thumbnails']['high']['url'], 'videoId' => $video['id']];
     }, array_values(array_filter($videosData['items'], function ($video) {
         return !isset($video['liveStreamingDetails']['actualEndTime']);
     })));
     if ($this->cache && $this->cacheTimeout > 0) {
         $this->cache->save($this->getCacheKey($channelId), $streams, $this->cacheTimeout);
     }
     return $streams;
 }
Example #19
0
 /**
  * Make API Call
  * @param  string $path  API Path
  * @param  array  $query Additional query parameters (optional)
  * @return GuzzleHttp\Response
  */
 public function fetch($path, array $query = [])
 {
     if (!$this->api instanceof Http) {
         $this->setupHttpClient();
     }
     return $this->api->get($path, ['query' => $query])->json();
 }
 public function testReport()
 {
     //  Arrange.
     $transport = new \Swift_SmtpTransport();
     $transport->setHost('mailtrap.io');
     $transport->setPort(2525);
     $transport->setUsername(getenv('MAILTRAP_USERNAME'));
     $transport->setPassword(getenv('MAILTRAP_PASSWORD'));
     $mailer = new Swift_Mailer($transport);
     $message = new Swift_Message();
     $message->addTo('*****@*****.**');
     $message->setFrom('*****@*****.**');
     $body = new Body(new VarCloner(), new CliDumper());
     $compiler = new Compiler(new CommonMarkConverter(), new CssToInlineStyles());
     $email = new Email($mailer, $message, $body, $compiler);
     $exception = new DomainException('Testing a domain exception');
     $extra = ['only' => 'testing12321'];
     // Act.
     $email->report($exception, $extra);
     // Assert.
     $message = $this->mailtrap->get('inboxes/' . getenv('MAILTRAP_INBOX') . '/messages')->json()[0];
     $this->assertSame('Exception: Testing a domain exception', $message['subject']);
     $this->assertContains('$email->report($exception, $extra);', $message['text_body']);
     $this->assertContains("exception 'DomainException' with message 'Testing a domain exception'", $message['text_body']);
     $this->assertContains('{main}', $message['text_body']);
     $this->assertContains('"only" => "testing12321"', $message['text_body']);
     $this->assertContains('_SERVER', $message['text_body']);
 }
 /**
  * @param string $uri
  * @param array  $query
  * @param array  $options
  *
  * @return Response
  */
 public function get($uri, array $query = [], array $options = [])
 {
     if (!empty($query)) {
         $options['query'] = $this->buildQuery($query);
     }
     return $this->guzzle->get($uri, $options);
 }
Example #22
0
 /**
  * Returns the response data from the Forecast.io in the
  * form of an array
  *
  * @param float $latitude
  * @param float $longitude
  * @param \DateTime $time
  *
  * @return array
  */
 public function getForecast($latitude, $longitude, \DateTime $time = null)
 {
     $this->requestedUrl = Overcast::API_ENDPOINT . Overcast::getApiKey() . '/' . $latitude . ',' . $longitude;
     $response = $this->guzzleClient->get($this->requestedUrl);
     $this->responseHeaders = ['cache' => ['maxAge' => (int) trim(substr($response->getHeader('cache-control'), strrpos($response->getHeader('cache-control'), '=') + 1)), 'expires' => $response->getHeader('expires')], 'responseTime' => (int) $response->getHeader('x-response-time'), 'apiCalls' => (int) $response->getHeader('x-forecast-api-calls')];
     return $response->json();
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $youtube = new Client();
     $searchResponse = json_decode($youtube->get('https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=' . $this->channelID . '&eventType=live&type=video&key=' . Config::get('services.youtube.key'))->getBody());
     $isLive = $searchResponse->pageInfo->totalResults != 0;
     // Determine the total number of viewers
     if ($isLive) {
         $videoResponse = json_decode($youtube->get('https://www.googleapis.com/youtube/v3/videos?part=liveStreamingDetails&id=' . $searchResponse->items[0]->id->videoId . '&key=' . Config::get('services.youtube.key'))->getBody());
         $viewers = $videoResponse->items[0]->liveStreamingDetails->concurrentViewers;
     } else {
         $viewers = 0;
     }
     // If the livestream is active now, and wasn't before, or vice versa, send an event
     if ($isLive && (Redis::hget('webcast', 'isLive') == 'false' || !Redis::hexists('webcast', 'isLive'))) {
         // Grab all the relevant SpaceX youtube Livestreams, and create an event
         $videos = $this->getMultipleYoutubeLivestreams($videoId);
         // $searchResponse->items[0]->id->videoId
         event(new WebcastStartedEvent($videos));
     } elseif (!$isLive && Redis::hget('webcast', 'isLive') == 'true') {
         // turn off the spacex webcast
         event(new WebcastEndedEvent("spacex", false));
     }
     // Set the Redis properties
     Redis::hmset('webcast', 'isLive', $isLive === true ? 'true' : 'false', 'viewers', $viewers);
     // Add to Database if livestream is active
     if ($isLive) {
         WebcastStatus::create(['viewers' => $viewers]);
     }
 }
 /**
  * Send get request to Postback URL for goal reaching
  * Example for postback url of HasOffers goal:
  *     http://algomonster.go2cloud.org/aff_goal?a=lsr&goal_id=2&transaction_id=TRANSACTION_ID
  *
  * @param array $params Should be consist of 'goal_id' and 'transaction_id'
  * @return object
  */
 public function trackGoal(array $params)
 {
     $url = $this->goalsTrackingUrl . '&' . http_build_query($params);
     /** @var \GuzzleHttp\Message\Response $response */
     $response = $this->httpClient->get($url);
     return $this->handleResponse($response);
 }
Example #25
0
 public function testServerReturn404()
 {
     try {
         $this->client->get('/abc.txt');
     } catch (GuzzleHttp\Exception\ClientException $ex) {
         $this->assertEquals(404, $ex->getResponse()->getStatusCode());
     }
 }
 /**
  * Request a URL an throw an exception if there is no response, otherwise handle JSON.
  *
  * @param $url
  *
  * @throws \Destiny\Support\Exceptions\BungieUnavailableException
  *
  * @return array
  */
 protected function requestJson($url)
 {
     $response = $this->http->get($url);
     if (!$response) {
         throw new BungieUnavailableException();
     }
     return $response->json();
 }
 private function sendShutdownCmd()
 {
     try {
         $this->httpClient->get($this->seleniumOptions->getSeleniumShutdownUrl(), $this->seleniumOptions->getSeleniumShutDownOptions());
     } catch (ConnectException $exc) {
         throw new \RuntimeException($exc->getMessage() . PHP_EOL . 'Probably selenium is already stopped.');
     }
 }
Example #28
0
 /**
  * 更改 ecourse session 中 course id 的值.
  *
  * @return $this
  */
 protected function touchSession()
 {
     if ($this->courseId !== Session::get('ccu.ecourse.courseId')) {
         $this->client->get(self::COURSES_SHOW, ['cookies' => $this->jar, 'query' => ['courseid' => $this->courseId]]);
         Session::put('ccu.ecourse.courseId', $this->courseId);
     }
     return $this;
 }
 public function testStaleIfErrorHeader()
 {
     $this->client->get("http://test.com/stale-if-error");
     $this->sendError = true;
     $response = $this->client->get("http://test.com/stale-if-error");
     $this->assertEquals("HIT stale", $response->getHeaderLine("X-Cache"));
     $this->sendError = false;
 }
Example #30
0
 /**
  * @since 2.0.0
  *
  * @param string $url e.g. https://en.wikipedia.org OR https://de.wikipedia.org/wiki/Berlin
  *
  * @return self returns a MediawikiApi instance using the apiEndpoint provided by the RSD
  *              file accessible on all Mediawiki pages
  *
  * @see https://en.wikipedia.org/wiki/Really_Simple_Discovery
  */
 public static function newFromPage($url)
 {
     $tempClient = new Client(array('headers' => array('User-Agent' => 'addwiki-mediawiki-client')));
     $pageXml = new SimpleXMLElement($tempClient->get($url)->getBody());
     $rsdElement = $pageXml->xpath('head/link[@type="application/rsd+xml"][@href]');
     $rsdXml = new SimpleXMLElement($tempClient->get($rsdElement[0]->attributes()['href'])->getBody());
     return self::newFromApiEndpoint($rsdXml->service->apis->api->attributes()->apiLink->__toString());
 }