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

[8.x] Add ability to customize json options on JsonResource response #40208

Merged
merged 3 commits into from
Jan 3, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
12 changes: 12 additions & 0 deletions src/Illuminate/Http/Resources/CollectsResources.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,16 @@ public function getIterator()
{
return $this->collection->getIterator();
}

/**
* Get the serialization options applied to the resource response.
*
* @return int
*/
public function jsonOptions()
{
$collects = $this->collects();

return $collects ? (new $collects([]))->jsonOptions() : 0;
}
}
10 changes: 10 additions & 0 deletions src/Illuminate/Http/Resources/Json/JsonResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,16 @@ public function additional(array $data)
return $this;
}

/**
* Get the serialization options applied to the resource response.
*
* @return int
*/
public function jsonOptions()
{
return 0;
bastien-phi marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Customize the response for a request.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ public function toResponse($request)
$this->resource->additional
)
),
$this->calculateStatus()
$this->calculateStatus(),
[],
$this->resource->jsonOptions()
), function ($response) use ($request) {
$response->original = $this->resource->resource->map(function ($item) {
return is_array($item) ? Arr::get($item, 'resource') : $item->resource;
Expand Down
4 changes: 3 additions & 1 deletion src/Illuminate/Http/Resources/Json/ResourceResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ public function toResponse($request)
$this->resource->with($request),
$this->resource->additional
),
$this->calculateStatus()
$this->calculateStatus(),
[],
$this->resource->jsonOptions()
), function ($response) use ($request) {
$response->original = $this->resource->resource;

Expand Down
22 changes: 22 additions & 0 deletions tests/Integration/Http/Fixtures/PostResourceWithJsonOptions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Illuminate\Tests\Integration\Http\Fixtures;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResourceWithJsonOptions extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'reading_time' => $this->reading_time,
];
}

public function jsonOptions()
{
return JSON_PRESERVE_ZERO_FRACTION;
bastien-phi marked this conversation as resolved.
Show resolved Hide resolved
}
}
60 changes: 60 additions & 0 deletions tests/Integration/Http/ResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Illuminate\Tests\Integration\Http\Fixtures\PostResource;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithAnonymousResourceCollectionWithPaginationInformation;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithExtraData;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithJsonOptions;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithOptionalAppendedAttributes;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithOptionalData;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithOptionalMerging;
Expand Down Expand Up @@ -495,6 +496,65 @@ public function testResourcesMayCustomizeExtraDataWhenBuildingResponse()
]);
}

public function testResourcesMayCustomizeJsonOptions()
{
Route::get('/', function () {
return new PostResourceWithJsonOptions(new Post([
'id' => 5,
'title' => 'Test Title',
'reading_time' => 3.0,
]));
});

$response = $this->withoutExceptionHandling()->get(
'/', ['Accept' => 'application/json']
);

$this->assertEquals(
'{"data":{"id":5,"title":"Test Title","reading_time":3.0}}',
$response->baseResponse->content()
);
}

public function testCollectionResourcesMayCustomizeJsonOptions()
{
Route::get('/', function () {
return PostResourceWithJsonOptions::collection(collect([
new Post(['id' => 5, 'title' => 'Test Title', 'reading_time' => 3.0]),
]));
});

$response = $this->withoutExceptionHandling()->get(
'/', ['Accept' => 'application/json']
);

$this->assertEquals(
'{"data":[{"id":5,"title":"Test Title","reading_time":3.0}]}',
$response->baseResponse->content()
);
}

public function testResourcesMayCustomizeJsonOptionsOnPaginatedResponse()
{
Route::get('/', function () {
$paginator = new LengthAwarePaginator(
collect([new Post(['id' => 5, 'title' => 'Test Title', 'reading_time' => 3.0])]),
10, 15, 1
);

return PostResourceWithJsonOptions::collection($paginator);
});

$response = $this->withoutExceptionHandling()->get(
'/', ['Accept' => 'application/json']
);

$this->assertEquals(
'{"data":[{"id":5,"title":"Test Title","reading_time":3.0}],"links":{"first":"\/?page=1","last":"\/?page=1","prev":null,"next":null},"meta":{"current_page":1,"from":1,"last_page":1,"links":[{"url":null,"label":"&laquo; Previous","active":false},{"url":"\/?page=1","label":"1","active":true},{"url":null,"label":"Next &raquo;","active":false}],"path":"\/","per_page":15,"to":1,"total":10}}',
$response->baseResponse->content()
);
}

public function testCustomHeadersMayBeSetOnResponses()
{
Route::get('/', function () {
Expand Down