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

[5.8] Check for preserveKeys when serializing a collection from a resource #27985

Merged
merged 2 commits into from
Mar 29, 2019
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
6 changes: 5 additions & 1 deletion src/Illuminate/Http/Resources/Json/JsonResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ public static function make(...$parameters)
*/
public static function collection($resource)
{
return new AnonymousResourceCollection($resource, static::class);
return tap(new AnonymousResourceCollection($resource, static::class), function ($collection) {
if (property_exists(static::class, 'preserveKeys')) {
$collection->preserveKeys = (new static([]))->preserveKeys === true;
}
});
}

/**
Expand Down
34 changes: 34 additions & 0 deletions tests/Integration/Http/ResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Illuminate\Tests\Integration\Http;

use Orchestra\Testbench\TestCase;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Resources\MergeValue;
use Illuminate\Http\Resources\MissingValue;
Expand Down Expand Up @@ -629,6 +630,39 @@ public function test_keys_are_preserved_if_the_resource_is_flagged_to_preserve_k
$response->assertJson(['data' => $data]);
}

public function test_keys_are_preserved_in_an_anonymous_colletion_if_the_resource_is_flagged_to_preserve_keys()
{
$data = Collection::make([
[
'id' => 1,
'authorId' => 5,
'bookId' => 22,
],
[
'id' => 2,
'authorId' => 5,
'bookId' => 15,
],
[
'id' => 3,
'authorId' => 42,
'bookId' => 12,
],
])->keyBy->id;

Route::get('/', function () use ($data) {
return ResourceWithPreservedKeys::collection($data);
});

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

$response->assertStatus(200);

$response->assertJson(['data' => $data->toArray()]);
}

public function test_leading_merge_keyed_value_is_merged_correctly()
{
$filter = new class {
Expand Down