public function batch(array $urls)
{
$multi = curl_multi_init();
$results = array();
// Create the curl handles and add them to the multi_request
foreach (array_values($urls) as $count => $uri) {
$results[$uri] = array();
${$count} = $this->handle($uri, $results[$uri]);
$code = curl_multi_add_handle($multi, ${$count});
if ($code != CURLM_OK) {
throw new \Exception("Curl handle for {$uri} could not be added");
}
}
// Perform the requests
do {
while (($mrc = curl_multi_exec($multi, $active)) == CURLM_CALL_MULTI_PERFORM) {
}
if ($mrc != CURLM_OK && $mrc != CURLM_CALL_MULTI_PERFORM) {
throw new \Exception("Curl error code: {$mrc}");
}
if ($active && curl_multi_select($multi) === -1) {
// Perform a usleep if a select returns -1.
// See: https://bugs.php.net/bug.php?id=61141
usleep(250);
}
} while ($active);
// Figure out why individual requests may have failed
foreach (array_values($urls) as $count => $uri) {
$error = curl_error(${$count});
if ($error) {
$results[$uri]['failure_reason'] = $error;
}
}
return $results;
}