当我尝试使用Guzzle下载许多图像时遇到问题。其中一些可能无效,因此当我发出AsyncRequest时,我无法处理每个图像的异常。
我试图制定一种验证方法,该方法必须适用于下载的文件,但不能按时工作。
$requests = function () use ($client, $imagesMetaData) {
foreach ($imagesMetaData as $index => $image) {
yield $index => function () use ($client, $image) {
try {
$resource = fopen($image['savePath'], 'w+b');
if (!$resource) {
// do smth
}
$opts = ['sink' => $resource];
$result = $client->requestAsync('GET', $image['downloadUri'], $opts);
return ($result);
} catch (\Exception $e) {
$image['writeLog'](
// do smth
);
return new Response(404);
}
};
}
};
Pool::batch($client, $requests(), [
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) use ($me, $imagesMetaData, &$fulfilled, &$rejected) {
$image = $imagesMetaData[$index];
foreach ($imagesMetaData as $image) {
if ($me->validateDownloadedImage($image)) {
$fulfilled[] = $image;
} else {
$rejected[] = $image;
}
}
},
'rejected' => function ($reason, $index) use ($me, $imagesMetaData, &$rejected) {
$image = $imagesMetaData[$index];
$me->rejectImage($image, $reason);
$rejected[] = $image;
}
]);
return [$fulfilled, $rejected];
如果文件图像很好-一切正常,但是如果其中一个失败-我有下一个错误
在第250行的文件/var/www/my.site/localhost/core/libraries/guzzlehttp/psr7/src/Stream.php中抛出了类型为RuntimeException的目录导入异常。无法写入流。
https://i.imgur.com/SBLpni5.png
如果有人知道这一点,请帮助。
答案 0 :(得分:0)
我通过打开流解决了此问题:
$stream = stream_for($resource);
将此流传递给“接收器” :
'sink' => $stream
最终代码如下:
$requests = function () use ($client, $imagesMetaData) {
foreach ($imagesMetaData as $index => $image) {
yield $index => function () use ($client, $image) {
try {
$resource = fopen($image['savePath'], 'w+b');
$stream = stream_for($resource);
if (!$resource) {
// do smth
}
$opts = ['sink' => $stream];
$result = $client->requestAsync('GET', $image['downloadUri'], $opts);
return ($result);
} catch (\Exception $e) {
$image['writeLog'](
// do smth
);
return new Response(404);
}
};
}
};
Pool::batch($client, $requests(), [
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) use ($me, $imagesMetaData, &$fulfilled, &$rejected) {
$image = $imagesMetaData[$index];
foreach ($imagesMetaData as $image) {
if ($me->validateDownloadedImage($image)) {
$fulfilled[] = $image;
} else {
$rejected[] = $image;
}
}
},
'rejected' => function ($reason, $index) use ($me, $imagesMetaData, &$rejected) {
$image = $imagesMetaData[$index];
$me->rejectImage($image, $reason);
$rejected[] = $image;
}
]);
return [$fulfilled, $rejected];