Optimize HttpClient when body is iterable

This commit is contained in:
Jérémy Derussé 2020-02-26 14:43:55 +01:00
parent 7995fed10b
commit 03b7743ff5
No known key found for this signature in database
GPG Key ID: 2083FA5758C473D2

View File

@ -271,17 +271,12 @@ trait HttpClientTrait
return http_build_query($body, '', '&', PHP_QUERY_RFC1738);
}
if ($body instanceof \Traversable) {
$body = function () use ($body) { yield from $body; };
if (\is_string($body)) {
return $body;
}
if ($body instanceof \Closure) {
$r = new \ReflectionFunction($body);
$body = $r->getClosure();
if ($r->isGenerator()) {
$body = $body(self::$CHUNK_SIZE);
$body = function () use ($body) {
$generatorToCallable = static function (\Generator $body): \Closure {
return static function () use ($body) {
while ($body->valid()) {
$chunk = $body->current();
$body->next();
@ -293,12 +288,30 @@ trait HttpClientTrait
return '';
};
};
if ($body instanceof \Generator) {
return $generatorToCallable($body);
}
if ($body instanceof \Traversable) {
return $generatorToCallable((static function ($body) { yield from $body; })($body));
}
if ($body instanceof \Closure) {
$r = new \ReflectionFunction($body);
$body = $r->getClosure();
if ($r->isGenerator()) {
$body = $body(self::$CHUNK_SIZE);
return $generatorToCallable($body);
}
return $body;
}
if (!\is_string($body) && !\is_array(@stream_get_meta_data($body))) {
if (!\is_array(@stream_get_meta_data($body))) {
throw new InvalidArgumentException(sprintf('Option "body" must be string, stream resource, iterable or callable, %s given.', \is_resource($body) ? get_resource_type($body) : \gettype($body)));
}