Skip to content

Commit 7b7dea7

Browse files
Determine external http response size without reading stream
1 parent c0fc321 commit 7b7dea7

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/Recorders/ExternalHttpRecorder/ExternalHttpRecorder.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Illuminate\Http\Client\Events\ConnectionFailed;
77
use Illuminate\Http\Client\Events\RequestSending;
88
use Illuminate\Http\Client\Events\ResponseReceived;
9+
use Illuminate\Http\Client\Response;
910
use Spatie\FlareClient\Recorders\ExternalHttpRecorder\ExternalHttpRecorder as BaseExternalHttpRecorder;
1011
use Spatie\FlareClient\Support\BackTracer;
1112
use Spatie\FlareClient\Support\Redactor;
@@ -34,12 +35,28 @@ public function boot(): void
3435

3536
$this->dispatcher->listen(ResponseReceived::class, fn (ResponseReceived $event) => $this->recordReceived(
3637
$event->response->status(),
37-
strlen($event->response->body()),
38+
$this->getResponseLength($event->response),
3839
$event->response->headers(),
3940
));
4041

4142
$this->dispatcher->listen(ConnectionFailed::class, fn (ConnectionFailed $event) => $this->recordConnectionFailed(
4243
$event->exception::class
4344
));
4445
}
46+
47+
/**
48+
* Determine the content length of the response without reading the stream.
49+
*/
50+
protected function getResponseLength(Response $response): ?int
51+
{
52+
if ($response->getHeaderLine('Transfer-Encoding') === 'chunked') {
53+
return null;
54+
}
55+
56+
if ($response->hasHeader('Content-Length')) {
57+
return (int) $response->getHeaderLine('Content-Length');
58+
}
59+
60+
return $response->toPsrResponse()->getBody()->getSize() ?: null;
61+
}
4562
}

0 commit comments

Comments
 (0)