Skip to content

Commit aa195a2

Browse files
authored
Merge pull request #5 from tlafon/adding-multithread-promises
Adding function getResponses - Concurrent Requests using Promises
2 parents 5d8252f + ef2af78 commit aa195a2

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

README.md

+19
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,25 @@ var_dump($result->getSpeedScore()); // 100
2121
var_dump($result->getUsabilityScore()); // 100
2222
```
2323

24+
### Using Concurrent Requests
25+
```php
26+
$urls = array(
27+
'http://example.com',
28+
'http://example2.com',
29+
'http://example3.com'
30+
);
31+
32+
$caller = new \PhpInsights\InsightsCaller('your-google-api-key-here', 'fr');
33+
$responses = $caller->getResponses($urls, \PhpInsights\InsightsCaller::STRATEGY_MOBILE);
34+
35+
foreach ($responses as $url=>$response) {
36+
$result = $response->getMappedResult();
37+
38+
var_dump($result->getSpeedScore()); // 100
39+
var_dump($result->getUsabilityScore()); // 100
40+
}
41+
```
42+
2443
### Result details
2544
#### Full result
2645
```php

src/InsightsCaller.php

+39
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
namespace PhpInsights;
33

44
use GuzzleHttp\Client;
5+
use GuzzleHttp\Promise;
56
use GuzzleHttp\Exception\TransferException;
67

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

7576
}
7677

78+
/**
79+
* @param array $urls
80+
* @param string $strategy
81+
*
82+
* @return InsightsResponse
83+
*
84+
* @throws ApiRequestException
85+
*/
86+
public function getResponses(array $urls, $strategy = 'mobile')
87+
{
88+
89+
try {
90+
$promises = array();
91+
92+
foreach ($urls as $k=>$url) {
93+
$apiEndpoint = $this->createApiEndpointUrl($url, $strategy);
94+
$promises[$k] = $this->client->getAsync($apiEndpoint);
95+
}
96+
97+
$results = Promise\unwrap($promises);
98+
$results = Promise\settle($promises)->wait();
99+
100+
$responses = array();
101+
102+
foreach ($urls as $k=>$url) {
103+
$response = $results[$k]['value'];
104+
$responses[$url] = InsightsResponse::fromResponse($response);
105+
}
106+
107+
108+
} catch (TransferException $e) {
109+
throw new ApiRequestException($e->getMessage());
110+
}
111+
112+
return $responses;
113+
114+
}
115+
77116
/**
78117
* @return boolean
79118
*/

0 commit comments

Comments
 (0)