Skip to content

Commit ffe4d6d

Browse files
authored
Do not transform JsonSerializable instances to array (#41077)
1 parent d649c09 commit ffe4d6d

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/Illuminate/Http/Client/PendingRequest.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use GuzzleHttp\Exception\RequestException;
99
use GuzzleHttp\Exception\TransferException;
1010
use GuzzleHttp\HandlerStack;
11+
use Illuminate\Contracts\Support\Arrayable;
1112
use Illuminate\Http\Client\Events\ConnectionFailed;
1213
use Illuminate\Http\Client\Events\RequestSending;
1314
use Illuminate\Http\Client\Events\ResponseReceived;
@@ -747,7 +748,13 @@ protected function parseHttpOptions(array $options)
747748
$options[$this->bodyFormat] = $this->pendingBody;
748749
}
749750

750-
return collect($options)->toArray();
751+
return collect($options)->map(function ($value, $key) {
752+
if ($key === 'json' && $value instanceof JsonSerializable) {
753+
return $value;
754+
}
755+
756+
return $value instanceof Arrayable ? $value->toArray() : $value;
757+
})->all();
751758
}
752759

753760
/**

tests/Http/HttpClientTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use GuzzleHttp\Promise\PromiseInterface;
77
use GuzzleHttp\Psr7\Response as Psr7Response;
88
use Illuminate\Contracts\Events\Dispatcher;
9+
use Illuminate\Contracts\Support\Arrayable;
910
use Illuminate\Http\Client\Events\RequestSending;
1011
use Illuminate\Http\Client\Events\ResponseReceived;
1112
use Illuminate\Http\Client\Factory;
@@ -221,6 +222,34 @@ public function jsonSerialize(): mixed
221222
});
222223
}
223224

225+
public function testPrefersJsonSerializableOverArrayableData()
226+
{
227+
$this->factory->fake();
228+
229+
$this->factory->asJson()->post('http://foo.com/form', new class implements JsonSerializable, Arrayable
230+
{
231+
public function jsonSerialize(): mixed
232+
{
233+
return [
234+
'attributes' => (object) [],
235+
];
236+
}
237+
238+
public function toArray(): array
239+
{
240+
return [
241+
'attributes' => [],
242+
];
243+
}
244+
});
245+
246+
$this->factory->assertSent(function (Request $request) {
247+
return $request->url() === 'http://foo.com/form' &&
248+
$request->hasHeader('Content-Type', 'application/json') &&
249+
$request->body() === '{"attributes":{}}';
250+
});
251+
}
252+
224253
public function testRecordedCallsAreEmptiedWhenFakeIsCalled()
225254
{
226255
$this->factory->fake([

0 commit comments

Comments
 (0)