Skip to content

Commit 640fa70

Browse files
committed
[HttpClient] Check status code before decoding in TraceableResponse::toArray()
1 parent a29af81 commit 640fa70

File tree

2 files changed

+25
-12
lines changed

2 files changed

+25
-12
lines changed

src/Symfony/Component/HttpClient/Response/TraceableResponse.php

+12-12
Original file line numberDiff line numberDiff line change
@@ -52,24 +52,24 @@ public function getHeaders(bool $throw = true): array
5252

5353
public function getContent(bool $throw = true): string
5454
{
55-
$this->content = $this->response->getContent(false);
56-
57-
if ($throw) {
58-
$this->checkStatusCode($this->response->getStatusCode());
55+
try {
56+
return $this->content = $this->response->getContent(false);
57+
} finally {
58+
if ($throw) {
59+
$this->checkStatusCode($this->response->getStatusCode());
60+
}
5961
}
60-
61-
return $this->content;
6262
}
6363

6464
public function toArray(bool $throw = true): array
6565
{
66-
$this->content = $this->response->toArray(false);
67-
68-
if ($throw) {
69-
$this->checkStatusCode($this->response->getStatusCode());
66+
try {
67+
return $this->content = $this->response->toArray(false);
68+
} finally {
69+
if ($throw) {
70+
$this->checkStatusCode($this->response->getStatusCode());
71+
}
7072
}
71-
72-
return $this->content;
7373
}
7474

7575
public function cancel(): void

src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php

+13
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use Symfony\Component\HttpClient\NativeHttpClient;
1717
use Symfony\Component\HttpClient\Response\MockResponse;
1818
use Symfony\Component\HttpClient\TraceableHttpClient;
19+
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
1920
use Symfony\Contracts\HttpClient\HttpClientInterface;
2021
use Symfony\Contracts\HttpClient\Test\TestHttpServer;
2122

@@ -100,4 +101,16 @@ public function testStream()
100101
$this->assertGreaterThan(1, \count($chunks));
101102
$this->assertSame('Symfony is awesome!', implode('', $chunks));
102103
}
104+
105+
public function testToArrayChecksStatusCodeBeforeDecoding()
106+
{
107+
$this->expectException(ClientExceptionInterface::class);
108+
109+
$sut = new TraceableHttpClient(new MockHttpClient($responseFactory = function (): MockResponse {
110+
return new MockResponse('Errored.', ['http_code' => 400]);
111+
}));
112+
113+
$response = $sut->request('GET', 'https://example.com/foo/bar');
114+
$response->toArray();
115+
}
103116
}

0 commit comments

Comments
 (0)