diff --git a/src/Serializer/JsonApiSerializer.php b/src/Serializer/JsonApiSerializer.php index e532d010..773f6a65 100644 --- a/src/Serializer/JsonApiSerializer.php +++ b/src/Serializer/JsonApiSerializer.php @@ -14,6 +14,7 @@ use InvalidArgumentException; use League\Fractal\Pagination\PaginatorInterface; use League\Fractal\Resource\ResourceInterface; +use UnexpectedValueException; class JsonApiSerializer extends ArraySerializer { @@ -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' => [ @@ -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']; diff --git a/test/Serializer/JsonApiSerializerTest.php b/test/Serializer/JsonApiSerializerTest.php index b3663ff3..c7fe2ad2 100644 --- a/test/Serializer/JsonApiSerializerTest.php +++ b/test/Serializer/JsonApiSerializerTest.php @@ -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');