Skip to content

Commit 29b8da3

Browse files
committed
Optimize HttpClient when body is iterable
1 parent af30b63 commit 29b8da3

File tree

1 file changed

+26
-13
lines changed

1 file changed

+26
-13
lines changed

HttpClientTrait.php

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -271,8 +271,31 @@ private static function normalizeBody($body)
271271
return http_build_query($body, '', '&', PHP_QUERY_RFC1738);
272272
}
273273

274+
if (\is_string($body)) {
275+
return $body;
276+
}
277+
278+
$generatorToCallable = static function (\Generator $body): \Closure {
279+
return static function () use ($body) {
280+
while ($body->valid()) {
281+
$chunk = $body->current();
282+
$body->next();
283+
284+
if ('' !== $chunk) {
285+
return $chunk;
286+
}
287+
}
288+
289+
return '';
290+
};
291+
};
292+
293+
if ($body instanceof \Generator) {
294+
return $generatorToCallable($body);
295+
}
296+
274297
if ($body instanceof \Traversable) {
275-
$body = function () use ($body) { yield from $body; };
298+
return $generatorToCallable((static function ($body) { yield from $body; })($body));
276299
}
277300

278301
if ($body instanceof \Closure) {
@@ -281,24 +304,14 @@ private static function normalizeBody($body)
281304

282305
if ($r->isGenerator()) {
283306
$body = $body(self::$CHUNK_SIZE);
284-
$body = function () use ($body) {
285-
while ($body->valid()) {
286-
$chunk = $body->current();
287-
$body->next();
288-
289-
if ('' !== $chunk) {
290-
return $chunk;
291-
}
292-
}
293307

294-
return '';
295-
};
308+
return $generatorToCallable($body);
296309
}
297310

298311
return $body;
299312
}
300313

301-
if (!\is_string($body) && !\is_array(@stream_get_meta_data($body))) {
314+
if (!\is_array(@stream_get_meta_data($body))) {
302315
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)));
303316
}
304317

0 commit comments

Comments
 (0)