Skip to content

Commit

Permalink
Do not transform JsonSerializable instances to array (#41077)
Browse files Browse the repository at this point in the history
  • Loading branch information
JaZo authored Feb 17, 2022
1 parent d649c09 commit ffe4d6d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
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

0 comments on commit ffe4d6d

Please sign in to comment.