Skip to content

Commit

Permalink
Merge pull request #5 from tlafon/adding-multithread-promises
Browse files Browse the repository at this point in the history
Adding function getResponses - Concurrent Requests using Promises
  • Loading branch information
dsentker authored Jun 11, 2018
2 parents 5d8252f + ef2af78 commit aa195a2
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,25 @@ var_dump($result->getSpeedScore()); // 100
var_dump($result->getUsabilityScore()); // 100
```

### Using Concurrent Requests
```php
$urls = array(
'http://example.com',
'http://example2.com',
'http://example3.com'
);

$caller = new \PhpInsights\InsightsCaller('your-google-api-key-here', 'fr');
$responses = $caller->getResponses($urls, \PhpInsights\InsightsCaller::STRATEGY_MOBILE);

foreach ($responses as $url=>$response) {
$result = $response->getMappedResult();

var_dump($result->getSpeedScore()); // 100
var_dump($result->getUsabilityScore()); // 100
}
```

### Result details
#### Full result
```php
Expand Down
39 changes: 39 additions & 0 deletions src/InsightsCaller.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
namespace PhpInsights;

use GuzzleHttp\Client;
use GuzzleHttp\Promise;
use GuzzleHttp\Exception\TransferException;

class InsightsCaller
Expand Down Expand Up @@ -74,6 +75,44 @@ public function getResponse($url, $strategy = 'mobile')

}

/**
* @param array $urls
* @param string $strategy
*
* @return InsightsResponse
*
* @throws ApiRequestException
*/
public function getResponses(array $urls, $strategy = 'mobile')
{

try {
$promises = array();

foreach ($urls as $k=>$url) {
$apiEndpoint = $this->createApiEndpointUrl($url, $strategy);
$promises[$k] = $this->client->getAsync($apiEndpoint);
}

$results = Promise\unwrap($promises);
$results = Promise\settle($promises)->wait();

$responses = array();

foreach ($urls as $k=>$url) {
$response = $results[$k]['value'];
$responses[$url] = InsightsResponse::fromResponse($response);
}


} catch (TransferException $e) {
throw new ApiRequestException($e->getMessage());
}

return $responses;

}

/**
* @return boolean
*/
Expand Down

0 comments on commit aa195a2

Please sign in to comment.