本文整理汇总了PHP中GuzzleHttp\Promise\unwrap函数的典型用法代码示例。如果您正苦于以下问题:PHP unwrap函数的具体用法?PHP unwrap怎么用?PHP unwrap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了unwrap函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: send
/**
* @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;
}
示例2: getAllProjects
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;
}
示例3: __invoke
/**
* __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;
}
示例4: foreach
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;
}
示例5: testGetProductsAsync
/**
* @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");
}
示例6: testEventDispatcherMulticlient
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);
}
示例7: parseLists
/**
* 分析公告列表.
*
* @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;
}
示例8: parseLists
/**
* 分析授課教材列表.
*
* @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;
}
示例9: __invoke
/**
* __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;
}
示例10: send
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;
}
}
示例11: parseLists
/**
* 分析作業列表.
*
* @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);
}
示例12: run
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;
}
示例13: multiRequest
/**
* @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;
}
示例14: send
/**
* @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;
}
示例15: requestJsons
/**
* 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;
}