Skip to content
Open
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
11 changes: 10 additions & 1 deletion src/Serializer/JsonApiSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use InvalidArgumentException;
use League\Fractal\Pagination\PaginatorInterface;
use League\Fractal\Resource\ResourceInterface;
use UnexpectedValueException;

class JsonApiSerializer extends ArraySerializer
{
Expand Down Expand Up @@ -45,6 +46,11 @@ public function collection(?string $resourceKey, array $data): array
public function item(?string $resourceKey, array $data): array
{
$id = $this->getIdFromData($data);
$resourceKey = $resourceKey ?? $data['type'];

if ($resourceKey === null) {
throw new UnexpectedValueException('The resource must have a key specified.');
}

$resource = [
'data' => [
Expand All @@ -54,7 +60,10 @@ public function item(?string $resourceKey, array $data): array
],
];

unset($resource['data']['attributes']['id']);
unset(
$resource['data']['attributes']['id'],
$resource['data']['attributes']['type']
);

if (isset($resource['data']['attributes']['links'])) {
$custom_links = $data['links'];
Expand Down
29 changes: 29 additions & 0 deletions test/Serializer/JsonApiSerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,35 @@ public function testSerializeCollectionWithExtraMeta()
$this->assertSame($expectedJson, $scope->toJson());
}

public function testSerializingItemResourceWithNestedType()
{
$bookData = [
'id' => 1,
'type' => 'books',
'title' => 'Foo',
'year' => '1991',
];

$resource = new Item($bookData, new JsonApiBookTransformer());
$scope = new Scope($this->manager, $resource);

$expected = [
'data' => [
'type' => 'books',
'id' => '1',
'attributes' => [
'title' => 'Foo',
'year' => 1991,
],
],
];

$this->assertSame($expected, $scope->toArray());

$expectedJson = '{"data":{"type":"books","id":"1","attributes":{"title":"Foo","year":1991}}}';
$this->assertSame($expectedJson, $scope->toJson());
}

public function testSerializingItemResourceWithHasOneInclude()
{
$this->manager->parseIncludes('author');
Expand Down