Ejemplo n.º 1
2
 /**
  * @inheritdoc
  */
 public function send()
 {
     $body = ['aps' => []];
     if ($this->messageData !== null) {
         $body['aps'] = $this->messageData;
     }
     if ($this->messageText !== null) {
         $body['aps']['alert'] = $this->messageText;
         if (!isset($body['aps']['sound'])) {
             $body['aps']['sound'] = 'default';
         }
         if (!isset($body['aps']['badge'])) {
             $body['aps']['badge'] = 0;
         }
     }
     $bodyData = json_encode($body);
     $ok = [];
     $promises = [];
     foreach ($this->recipients as $recipient) {
         $url = sprintf('/3/device/%s', $recipient);
         $promises[] = $this->client->postAsync($url, ['body' => $bodyData])->then(function (ResponseInterface $response) use(&$ok, $recipient) {
             if ($response->getStatusCode() == 200) {
                 // Set to OK if we received a 200
                 $ok[] = $recipient;
             } else {
                 $this->failedRecipients[] = $recipient;
             }
         }, function () use($recipient) {
             $this->failedRecipients[] = $recipient;
         });
     }
     // Wait for all requests to complete
     Promise\unwrap($promises);
     return $ok;
 }
Ejemplo n.º 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;
 }
 /**
  * __invoke.
  *
  * @param mixed $values
  *
  * @return $this
  */
 public function __invoke($values)
 {
     $response = json_decode((string) $values->getBody());
     // Return when empty response.
     if (empty($response)) {
         return $this;
     }
     // Process the response.
     $this->process($response);
     $promisses = [];
     // Loop over all artist and create promisses
     foreach ($this->getArtistsAlbumsList() as $artistEntity) {
         $artistEntity = $artistEntity[0];
         // Process offset value only one time.
         if (isset($this->processedArtistsList[$artistEntity->id]) && $this->processedArtistsList[$artistEntity->id] === true) {
             continue;
         } else {
             $getArtistRelatedArtists = 'artists/' . $artistEntity->id . '/related-artists';
             $promisses[] = $this->client->getAsync($getArtistRelatedArtists)->then($this);
             // <= re-use same object.
             $this->processedArtistsList[$artistEntity->id] = true;
         }
     }
     // Resolve promisses.
     Promise\unwrap($promisses);
     return $this;
 }
Ejemplo n.º 4
0
 function upload_async($objects = [])
 {
     if (empty($objects)) {
         $this->error = ['message' => 'object array is empty'];
         return NULL;
     }
     $promises = [];
     foreach ($objects as $id => $object) {
         // $key = 'data.txt', $body = 'Hello!'
         // Executing an operation asynchronously returns a Promise object.
         $promises[$id] = $this->s3_client->putObjectAsync(['Bucket' => $this->bucket, 'Key' => $object['key'], 'Body' => $object['body'], 'ContentType' => $object['content-type']]);
     }
     // Wait for the operation to complete to get the Result object.
     try {
         $results = Promise\unwrap($promises);
     } catch (AwsException $e) {
         // handle the error.
         $error_msg = 'getAwsRequestId: ' . $e->getAwsRequestId() . ', getAwsErrorType:' . $e->getAwsErrorType() . ', getAwsErrorCode:' . $e->getAwsErrorCode() . "\n\n";
         $error_msg .= $e->getMessage() . "\n";
         $error_msg .= $e->getTraceAsString();
     }
     // if (!empty($this->error)) echo $error_msg['message']; else var_dump($results); die();
     if (!empty($error_msg)) {
         $this->error = ['message' => $error_msg];
         return NULL;
     }
     $response = [];
     foreach ($results as $id => $result) {
         if (!empty($result['ObjectURL'])) {
             $response[$id] = $result['ObjectURL'];
         }
     }
     return $response;
 }
Ejemplo n.º 5
0
 /**
  * @covers Mozu\Api\Resources\Commerce\Catalog\Admin\ProductResource::getProducts
  * @todo Implement testGetProducts().
  */
 public function testGetProductsAsync()
 {
     $promises = ["product1" => $this->object->getProductAsync("AIRMOTION-SCIENCES-BSF09"), "product2" => $this->object->getProductAsync("AIRMOTION-SCIENCES-BSF12"), "product3" => $this->object->getProductAsync("AIRMOTION-SCIENCES-BSF15")];
     $results = Promise\unwrap($promises);
     $this->assertSame($results["product1"]->json()->productCode, "AIRMOTION-SCIENCES-BSF09");
     $this->assertSame($results["product2"]->json()->productCode, "AIRMOTION-SCIENCES-BSF12");
     $this->assertSame($results["product3"]->json()->productCode, "AIRMOTION-SCIENCES-BSF15");
 }
 public function testEventDispatcherMulticlient()
 {
     $mockDispatcher = new \mock\Symfony\Component\EventDispatcher\EventDispatcherInterface();
     $container = $this->getContainerForConfiguation('multiclient-config');
     $container->set('event_dispatcher', $mockDispatcher);
     $container->compile();
     $this->if($client = $container->get('m6web_guzzlehttp'))->and($client2 = $container->get('m6web_guzzlehttp_myclient'))->and($promises = ['test' => $client->getAsync('http://httpbin.org'), 'test2' => $client->getAsync('http://httpbin.org/ip')])->and($rep = Promise\unwrap($promises))->and($client2->get('http://httpbin.org'))->then->mock($mockDispatcher)->call('dispatch')->exactly(3);
 }
Ejemplo n.º 7
0
 /**
  * 分析公告列表.
  *
  * @param string $content
  * @return array
  */
 protected function parseLists($content)
 {
     $rows = array_slice(HtmlDomParser::str_get_html($content)->find('table table[bordercolordark] tr'), 1, 5);
     $result = $promises = [];
     foreach ($rows as $row) {
         $result[] = ['date' => trim($row->children(0)->plaintext), 'title' => html_entity_decode(trim($row->children(2)->plaintext), ENT_QUOTES, 'UTF-8')];
         $promises[] = $this->client->getAsync(self::CONTENT, ['cookies' => $this->jar, 'query' => ['a_id' => substr(strrchr(strstr($row->find('a', 0)->outertext, '&system', true), '='), 1)]]);
     }
     $response = Promise\unwrap($promises);
     for ($i = 0, $size = count($result); $i < $size; ++$i) {
         $result[$i]['content'] = $this->parseContent($response[$i]->getBody()->getContents());
     }
     return $result;
 }
Ejemplo n.º 8
0
 /**
  * 分析授課教材列表.
  *
  * @param $content
  * @return array
  */
 public function parseLists($content)
 {
     $rows = HtmlDomParser::str_get_html($content)->find('a[href]');
     $result = $promises = [];
     foreach ($rows as $row) {
         $promises[] = $this->client->getAsync(self::CONTENT . $row->href, ['http_errors' => false, 'cookies' => $this->jar]);
     }
     $responses = Promise\unwrap($promises);
     foreach ($responses as $response) {
         if (200 === $response->getStatusCode()) {
             $result = array_merge($result, $this->parseContent($response->getBody()->getContents()));
         }
     }
     return $result;
 }
 /**
  * __invoke.
  *
  * @param mixed $values
  *
  * @return $this
  */
 public function __invoke($values)
 {
     // Get from previous handler the artists albums list.
     $this->artistsAlbumsList = $values->getArtistsAlbumsList();
     $promisses = [];
     // Loop over the artists albums list creating promisses for each artist.
     foreach ($this->artistsAlbumsList as $artistId => $artistAlbum) {
         $artistsTopTracks = 'artists/' . $artistId . '/top-tracks?country=US';
         $promisses[$artistId] = $this->client->getAsync($artistsTopTracks);
     }
     // Resolve all promisses.
     $artistAlbums = Promise\unwrap($promisses);
     // Process the result.
     $this->process($artistAlbums);
     return $this;
 }
Ejemplo n.º 10
0
 function send($requests)
 {
     // 1. send emails async
     $this->CI->load->library('composer/lib_aws');
     $ses_client = $this->CI->lib_aws->get_ses();
     $promises = [];
     foreach ($requests as $request) {
         echo '(' . $request['request_id'] . ') Sending message: ' . $request['subject'] . ', to: ' . $request['to_email'] . PHP_EOL;
         // @debug: send to *@users.noreply.rime.co
         // $request['to_email'] = 'user-'.md5($request['to_email']).'@users.noreply.rime.co';
         $raw_message = ses_raw_email($request);
         // var_dump($raw_message); die();
         $email = ['RawMessage' => array('Data' => $raw_message)];
         $promises[$request['request_id']] = $ses_client->sendRawEmailAsync($email);
     }
     // Wait on promises to complete and return the results.
     try {
         $results = Promise\unwrap($promises);
     } catch (AwsException $e) {
         // handle the error.
         $error_msg = 'getAwsRequestId: ' . $e->getAwsRequestId() . ', getAwsErrorType:' . $e->getAwsErrorType() . ', getAwsErrorCode:' . $e->getAwsErrorCode() . "\n\n";
         $error_msg .= $e->getMessage() . "\n";
         $error_msg .= $e->getTraceAsString();
     }
     if (!empty($results)) {
         // 2. save messege_id
         $message_sent_list = [];
         foreach ($results as $request_id => $result) {
             echo '(' . $request_id . ') statusCode: ' . $result['@metadata']['statusCode'] . ', MessageId: ' . $result['MessageId'] . PHP_EOL;
             if (!empty($result['@metadata']['statusCode']) and $result['@metadata']['statusCode'] == 200 and !empty($result['MessageId'])) {
                 $ses_message_id = $result['MessageId'];
                 $message_sent_list[] = ['request_id' => $request_id, 'sent' => date('Y-m-d H:i:s'), 'ses_message_id' => $ses_message_id, 'archived' => date('Y-m-d H:i:s'), 'body_html' => NULL, 'body_text' => NULL];
             }
         }
         // mark sent
         if (!empty($message_sent_list)) {
             $this->CI->model_archive->update_batch($message_sent_list);
         }
     }
     if (!empty($error_msg)) {
         $this->error = ['message' => $error_msg];
         return NULL;
     } else {
         return TRUE;
     }
 }
Ejemplo n.º 11
0
 /**
  * 分析作業列表.
  *
  * @param string $content
  * @return array
  */
 protected function parseLists($content)
 {
     $rows = array_slice(HtmlDomParser::str_get_html($content)->find('table table tr'), 1);
     $result = $promises['content'] = $promises['submitted'] = [];
     foreach ($rows as $row) {
         $id = substr(strrchr(strstr($row->children(2)->innertext, '&action', true), '='), 1);
         $result[] = ['name' => trim($row->children(1)->plaintext), 'date' => trim($row->children(3)->plaintext)];
         $promises['content'][] = $this->client->getAsync(self::LISTS, ['allow_redirects' => false, 'cookies' => $this->jar, 'query' => ['work_id' => $id, 'action' => 'showwork']]);
         $promises['submitted'][] = $this->client->getAsync(self::LISTS, ['cookies' => $this->jar, 'query' => ['work_id' => $id, 'action' => 'seemywork']]);
     }
     $response['content'] = Promise\unwrap($promises['content']);
     $response['submitted'] = Promise\unwrap($promises['submitted']);
     for ($i = 0, $size = count($result); $i < $size; ++$i) {
         $result[$i]['submitted'] = $this->parseSubmitted($response['submitted'][$i]->getBody()->getContents());
         if ($response['content'][$i]->hasHeader('location')) {
             $result[$i]['link'] = self::BASE_URL . '/' . $response['content'][$i]->getHeaderLine('location');
         } else {
             $result[$i]['content'] = $this->parseContent($response['content'][$i]->getBody()->getContents());
         }
     }
     return array_reverse($result);
 }
Ejemplo n.º 12
0
 function run($startPage = 'http://streeteasy.com/for-sale/downtown/status:closed%7Clisted%3C1500')
 {
     $nextPage = $startPage;
     $promise = [$this->http->requestAsync('GET', $nextPage)];
     $urls = [];
     $i = 0;
     do {
         $result = Promise\unwrap($promise);
         $content = $result[0]->getBody();
         $this->html->load($content);
         $nextPage = $this->parseNextUrl($this->html);
         $promise = [$this->http->requestAsync('GET', $nextPage)];
         $urls = $this->parseUrls($this->html);
         print_r($urls);
         $this->parseDetails($urls);
         echo "nextPage={$nextPage}\n";
         if ($i++ >= 1) {
             break;
         }
     } while ($nextPage);
     return $this->details;
 }
Ejemplo n.º 13
0
 /**
  * @inheritdoc
  */
 public function multiRequest(array $urls)
 {
     $client = new Client();
     $promises = array();
     foreach ($urls as $urlName => $urlData) {
         if (is_string($urlData)) {
             $urlData = array($urlData, array());
         }
         $urlOptions = new Options($urlData[1]);
         $method = $urlOptions->get('method', 'GET', 'up');
         $args = $urlOptions->get('args');
         $url = 'GET' === $method ? Url::addArg((array) $args, $urlData[0]) : $urlData[0];
         $promises[$urlName] = $client->requestAsync($method, $url, $this->_getClientOptions($urlOptions, $method, $args));
     }
     $httpResults = Promise\unwrap($promises);
     /** @var string $resName */
     /** @var Response $httpResult */
     $result = array();
     foreach ($httpResults as $resName => $httpResult) {
         $result[$resName] = array($httpResult->getStatusCode(), $httpResult->getHeaders(), $httpResult->getBody()->getContents());
     }
     return $result;
 }
Ejemplo n.º 14
0
 /**
  * @inheritdoc
  */
 public function send()
 {
     $body = ['data' => []];
     if ($this->messageData !== null) {
         $body['data'] = $this->messageData;
     }
     if ($this->messageText !== null) {
         $body['data']['message'] = $this->messageText;
     }
     $ok = [];
     $promises = [];
     $recipients_chunked = array_chunk($this->recipients, 1000);
     foreach ($recipients_chunked as $recipients_part) {
         $body['registration_ids'] = $recipients_part;
         $promises[] = $this->client->postAsync('/gcm/send', ['body' => json_encode($body)])->then(function (ResponseInterface $response) use(&$ok, $recipients_part) {
             if ($response->getStatusCode() == 200) {
                 // Set to OK if we received a 200
                 $contents = json_decode($response->getBody()->getContents(), true);
                 $results = $contents['results'];
                 foreach ($recipients_part as $idx => $recipient) {
                     if (isset($results[$idx]['message_id']) && !isset($results[$idx]['error'])) {
                         $ok[] = $recipient;
                     } else {
                         $this->failedRecipients[] = $recipient;
                     }
                 }
             }
         }, function () use($recipients_part) {
             foreach ($recipients_part as $idx => $recipient) {
                 $this->failedRecipients[] = $recipient;
             }
         });
     }
     // Wait for all requests to complete
     Promise\unwrap($promises);
     return $ok;
 }
Ejemplo n.º 15
0
 /**
  * Create and send an HTTP request and return the decoded JSON response
  * body
  *
  * @throws EWSClientError
  *
  * @param string $method
  *   HTTP method e.g. GET, POST, DELETE
  * @param array  $uris
  *   URI strings
  * @param array  $options
  *   Request options to apply
  * @return mixed
  *   JSON decoded body from EWS
  */
 public function requestJsons($method, $uris, array $options = [])
 {
     // Add the OAuth access token to the request headers
     $options = array_merge($options, ['headers' => ['Authorization' => 'Bearer ' . $this->accessToken]]);
     /** @var Promise\PromiseInterface[] $promises */
     $promises = [];
     $transactionIds = [];
     $counter = 0;
     foreach ($uris as $uri) {
         $transactionIds[] = Uuid::uuid4()->toString();
         $this->logRequest($transactionIds[$counter], $method, $uri, $options);
         $promises[] = $this->http->requestAsync($method, $uri, $options);
     }
     try {
         $responses = Promise\unwrap($promises);
         $results = [];
         $counter = 0;
         foreach ($responses as $response) {
             $this->logResponse($transactionIds[$counter], $method, $uris[$counter], $response);
             $results[] = $this->handleResponse($response);
             $counter++;
         }
     } catch (ClientException $e) {
         throw new EWSClientError($e->getCode() . ' error', 0, null, []);
     }
     return $results;
 }
Ejemplo n.º 16
0
 /**
  * @param Finder          $finder      finder primmed with files to import
  * @param OutputInterface $output      output interfac
  * @param string          $host        host to import into
  * @param string          $rewriteHost string to replace with value from $rewriteTo during loading
  * @param string          $rewriteTo   string to replace value from $rewriteHost with during loading
  * @param boolean         $sync        send requests syncronously
  *
  * @return void
  *
  * @throws MissingTargetException
  */
 protected function importPaths(Finder $finder, OutputInterface $output, $host, $rewriteHost, $rewriteTo, $sync = false)
 {
     $promises = [];
     foreach ($finder as $file) {
         $doc = $this->frontMatter->parse($file->getContents());
         $output->writeln("<info>Loading data from {$file}</info>");
         if (!array_key_exists('target', $doc->getData())) {
             throw new MissingTargetException('Missing target in \'' . $file . '\'');
         }
         $targetUrl = sprintf('%s%s', $host, $doc->getData()['target']);
         $promises[] = $this->importResource($targetUrl, (string) $file, $output, $doc, $host, $rewriteHost, $rewriteTo, $sync);
     }
     try {
         Promise\unwrap($promises);
     } catch (\GuzzleHttp\Exception\ClientException $e) {
         // silently ignored since we already output an error when the promise fails
     }
 }
Ejemplo n.º 17
0
<?php

require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
$client = new Client();
// Initiate each request but do not block
$promises = ['yahoo' => $client->getAsync('http://www.yahoo.co.jp/'), 'passmarket' => $client->getAsync('http://passmarket.yahoo.co.jp/')];
// Wait on all of the requests to complete.
$results = Promise\unwrap($promises);
echo $results['yahoo']->getBody();
echo $results['passmarket']->getBody();
Ejemplo n.º 18
0
 /**
  * Send awaiting requests
  */
 protected function sendRequests()
 {
     if (count($this->promises) === count($this->filterSources(Source::STATUS_WAITING))) {
         $toSend = [];
         foreach ($this->promises as $key => $promise) {
             if (count($toSend) === $this->concurrency) {
                 break;
             }
             $toSend[$key] = $promise;
             unset($this->promises[$key]);
         }
         if (empty($toSend)) {
             return;
         }
         $this->log('Sending awaiting requests');
         $responses = Promise\unwrap($toSend);
         foreach ($responses as $key => $response) {
             $this->sources[$key]->response($response);
         }
     }
 }
Ejemplo n.º 19
0
 /**
  * Send the request
  *
  * @param      $promises
  * @param bool $isRelationAction
  *
  * @return array|bool|\Illuminate\Support\Collection
  */
 protected function send($promises, $isRelationAction = false)
 {
     try {
         return $results = Promise\unwrap($promises);
     } catch (RequestException $e) {
         print_r($e->getRequest()->getMethod() . ' ' . (string) $e->getRequest()->getUri() . PHP_EOL);
         print_r(json_decode($e->getRequest()->getBody(), true));
         print_r(json_decode($e->getResponse()->getBody(), true));
         return false;
     }
 }
Ejemplo n.º 20
0
 /**
  * Выполнение ассинхронных запросов
  * @param $requests
  * @return GisResponse[]
  * @throws GisRequestException
  */
 public function getAsync($requests)
 {
     $result = [];
     $index = 0;
     // разбиваем по 10 запросов
     foreach (array_chunk($requests, 10) as $chunk) {
         $promises = [];
         foreach ($chunk as $request) {
             /** @var $params BaseParams */
             $params = $request['params'];
             $params->setKey($this->apiKey);
             $promises[$index] = $this->client->getAsync($request['url'], ['query' => $params->toArray()]);
             $index++;
         }
         foreach (Promise\unwrap($promises) as $i => $response) {
             $result[$i] = $this->formatResponse($response);
         }
         //Пауза нужна, иначе блочат ключ
         // @todo продумать задержки :-(
         sleep(1);
     }
     return $result;
 }
Ejemplo n.º 21
0
 /**
  * Get reviews from country App Store
  *
  * @param  integer $appId
  * @param  string  $countryCode
  * @param  string  $countryName
  * @return array   list of reviews
  */
 public function getReviewsByCountry($appId, $countryCode, $countryName)
 {
     $reviews = [];
     $promises = [];
     for ($i = 1; $i <= $this->maxPages; $i++) {
         $promises['page' . $i] = $this->client->getAsync("https://itunes.apple.com/{$countryCode}/rss/customerreviews/page={$i}/id={$appId}/sortBy=mostRecent/json");
     }
     try {
         $responses = Promise\unwrap($promises);
         for ($page = 1; $page <= $this->maxPages; $page++) {
             $reviewsData = json_decode((string) $responses['page' . $page]->getBody(), true);
             if (!isset($reviewsData['feed']) || !isset($reviewsData['feed']['entry']) || count($reviewsData['feed']['entry']) == 0) {
                 // Received empty page
                 if ($this->logger) {
                     $this->logger->debug("#{$appId}: Received 0 entries for page {$page} in {$countryName}");
                 }
             } else {
                 if ($this->logger) {
                     $countEntries = count($reviewsData['feed']['entry']) - 1;
                     $this->logger->debug("#{$appId}: Received {$countEntries} entries for page {$page} in {$countryName}");
                 }
                 $applicationData = [];
                 foreach ($reviewsData['feed']['entry'] as $reviewEntry) {
                     if (isset($reviewEntry['im:name']) && isset($reviewEntry['im:image']) && isset($reviewEntry['link'])) {
                         // First element is always an app metadata
                         $applicationData = ['name' => $reviewEntry['im:name']['label'], 'image' => end($reviewEntry['im:image'])['label'], 'link' => $reviewEntry['link']['attributes']['href']];
                         continue;
                     }
                     $reviewId = intval($reviewEntry['id']['label']);
                     if ($this->storage->get("r{$reviewId}")) {
                         continue;
                     }
                     $review = ['id' => $reviewId, 'author' => ['uri' => $reviewEntry['author']['uri']['label'], 'name' => $reviewEntry['author']['name']['label']], 'title' => $reviewEntry['title']['label'], 'content' => $reviewEntry['content']['label'], 'rating' => intval($reviewEntry['im:rating']['label']), 'country' => $countryName, 'application' => array_merge($applicationData, ['version' => $reviewEntry['im:version']['label']])];
                     array_push($reviews, $review);
                 }
             }
         }
     } catch (Exception $e) {
         if ($this->logger) {
             $this->logger->error('Reviewer: exception while getting reviews', ['exception' => $e]);
         }
     }
     return $reviews;
 }
Ejemplo n.º 22
0
 /**
  * By Concurrent requests, to get all the data.
  *
  * @return Array
  */
 public function getAll()
 {
     $requests = ['schedule' => $this->buildGetRequest(self::ZF_SCHEDULE_URI, [], $this->headers, true), 'cet' => $this->buildGetRequest(self::ZF_CET_URI, [], $this->headers, true), 'exam' => $this->buildGetRequest(self::ZF_EXAM_URI, [], $this->headers, true)];
     // Wait on all of the requests to complete. Throws a ConnectException
     // if any of the requests fail
     $results = Promise\unwrap($requests);
     // Wait for the requests to complete, even if some of them fail
     // $results = Promise\settle($requests)->wait();
     //Parser the data we need.
     $schedule = $this->parserSchedule($results['schedule']->getBody());
     $cet = $this->parserCommonTable($results['cet']->getBody());
     $exam = $this->parserCommonTable($results['exam']->getBody());
     return compact('schedule', 'cet', 'exam');
 }
 /**
  * Query by gps
  * @param  float $lat latitude
  * @param  float $lng longitude
  * @return json
  */
 public function gps($lat, $lng)
 {
     $googReq = GoogleAPI::address($lat . ',' . $lng);
     $stateReq = StateAPI::gps($lat, $lng, ['boundary_id']);
     $resp = new \stdClass();
     $results = Promise\unwrap([$googReq, $stateReq]);
     if (isset($results[0]->status) && $results[0]->status == "error") {
         return $this->error($results[0]->message);
     }
     $divisions = array_unique(array_merge($results[0]->divisions, array_pluck($results[1], 'division')));
     $reps = Representative::whereIn('division', $divisions)->get()->all();
     usort($reps, 'rankSort');
     $resp->reps = $reps;
     if (isset($results[0]->location)) {
         $resp->location = $results[0]->location;
         if (isset($resp->location->state) && isset(Location::states[$resp->location->state])) {
             $resp->location->state_name = Location::states[$resp->location->state];
         }
     }
     return response()->json($resp);
 }
Ejemplo n.º 24
0
 public function request(int $batchSize = 10)
 {
     $this->checkRequirements();
     $results = Promise\unwrap($this->yieldAsyncPromisesForPostRequests($batchSize));
     foreach ($results as $index => $result) {
         foreach ($this->processResponse($index, json_decode($result->getBody()->getContents())) as $key => $response) {
             (yield $key => $response);
         }
     }
 }
Ejemplo n.º 25
0
 public function update(array $reps)
 {
     $divisions = [];
     foreach ($reps as $rep) {
         if (!empty($rep->division) && !in_array($rep->division, $divisions)) {
             array_push($divisions, $rep->division);
         }
     }
     $requests = array_map(function ($d) {
         return GoogleAPI::division($d);
     }, $divisions);
     $results = Promise\unwrap($requests);
     return array_collapse(array_map(function ($result) {
         return $result->reps;
     }, $results));
 }
Ejemplo n.º 26
0
 /**
  * Create and send an HTTP request and return the decoded JSON response
  * body
  *
  * @throws EWSClientError
  *
  * @param string $method
  *   HTTP method e.g. GET, POST, DELETE
  * @param array $uris
  *   URI strings
  * @param array $options
  *   Request options to apply
  * @return mixed
  *   JSON decoded body from EWS
  */
 public function requestJsons($method, $uris, array $options = [])
 {
     // Add the OAuth access token to the request headers
     $options = array_merge($options, ['headers' => ['Authorization' => 'Bearer ' . $this->accessToken]]);
     $promises = [];
     foreach ($uris as $uri) {
         $promises[] = $this->http->requestAsync($method, $uri, $options);
     }
     try {
         $responses = Promise\unwrap($promises);
         $results = [];
         foreach ($responses as $response) {
             $results[] = $this->handleResponse($response);
         }
     } catch (ClientException $e) {
         throw new EWSClientError($e->getCode() . ' error', 0, null, []);
     }
     return $results;
 }
Ejemplo n.º 27
0
 /**
  * Unwrap Promises.
  */
 public function __destruct()
 {
     Promise\unwrap(self::$promises);
 }
Ejemplo n.º 28
0
 /**
  * Function unwinds the request pool waiting for all requests to be completed (or timeout)
  * returning an array of response objects indexed against the key values that were used when the
  * promises were added to the pool
  * @return  \GuzzleHttp\Psr7\Response []
  */
 public function unwrap()
 {
     $results = Promise\unwrap($this->promises);
     return $results;
 }
Ejemplo n.º 29
0
 /**
  * Pass undefined requests to client
  *
  * @param string $method
  * @param arary  $args
  *
  * @return \GuzzleHttp\Psr7\Response
  */
 public function __call($method, $args)
 {
     $paths = isset($args[0]) ? $args[0] : false;
     $params = isset($args[1]) ? $args[1] : [];
     if (substr($method, -4) === 'Many') {
         $promises = [];
         foreach ($paths as $path) {
             $promises[$path] = $this->client->requestAsync(substr($method, 0, -4), '/' . $path, $params);
         }
         return Promise\unwrap($promises);
     }
     return $this->client->request($method, $paths ? '/' . $paths : null, $params);
 }
Ejemplo n.º 30
0
 /**
  * @param int $iCount
  * @return array
  */
 public function getBatchUsers($iCount = 10)
 {
     $aResults = [];
     $aPromises = $this->getBulkRequests($iCount);
     // Wait on all of the requests to complete.
     $aPromiseResults = Promise\unwrap($aPromises);
     foreach ($aPromiseResults as $oResponse) {
         // this is delivered each successful response
         /** @var ResponseInterface $oResponse */
         /** @var array $sBody */
         $sBody = $this->getBodyFromResponse($oResponse);
         $aResults[] = $this->transformResponseToTransformer($sBody);
     }
     return $aResults;
 }