Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Do not transform JsonSerializable instances to array in HTTP client methods #41077

Merged
merged 1 commit into from
Feb 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/Illuminate/Http/Client/PendingRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\TransferException;
use GuzzleHttp\HandlerStack;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Client\Events\ConnectionFailed;
use Illuminate\Http\Client\Events\RequestSending;
use Illuminate\Http\Client\Events\ResponseReceived;
Expand Down Expand Up @@ -747,7 +748,13 @@ protected function parseHttpOptions(array $options)
$options[$this->bodyFormat] = $this->pendingBody;
}

return collect($options)->toArray();
return collect($options)->map(function ($value, $key) {
if ($key === 'json' && $value instanceof JsonSerializable) {
return $value;
}

return $value instanceof Arrayable ? $value->toArray() : $value;
})->all();
}

/**
Expand Down
29 changes: 29 additions & 0 deletions tests/Http/HttpClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Response as Psr7Response;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Client\Events\RequestSending;
use Illuminate\Http\Client\Events\ResponseReceived;
use Illuminate\Http\Client\Factory;
Expand Down Expand Up @@ -221,6 +222,34 @@ public function jsonSerialize(): mixed
});
}

public function testPrefersJsonSerializableOverArrayableData()
{
$this->factory->fake();

$this->factory->asJson()->post('http://foo.com/form', new class implements JsonSerializable, Arrayable
{
public function jsonSerialize(): mixed
{
return [
'attributes' => (object) [],
];
}

public function toArray(): array
{
return [
'attributes' => [],
];
}
});

$this->factory->assertSent(function (Request $request) {
return $request->url() === 'http://foo.com/form' &&
$request->hasHeader('Content-Type', 'application/json') &&
$request->body() === '{"attributes":{}}';
});
}

public function testRecordedCallsAreEmptiedWhenFakeIsCalled()
{
$this->factory->fake([
Expand Down