Skip to content

Commit 489d24f

Browse files
author
kordum
committed
Added the ability to specify the resource type in the resource data
1 parent 573ca2e commit 489d24f

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/Serializer/JsonApiSerializer.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use InvalidArgumentException;
1515
use League\Fractal\Pagination\PaginatorInterface;
1616
use League\Fractal\Resource\ResourceInterface;
17+
use UnexpectedValueException;
1718

1819
class JsonApiSerializer extends ArraySerializer
1920
{
@@ -45,6 +46,11 @@ public function collection(?string $resourceKey, array $data): array
4546
public function item(?string $resourceKey, array $data): array
4647
{
4748
$id = $this->getIdFromData($data);
49+
$resourceKey = $resourceKey ?? $data['type'];
50+
51+
if ($resourceKey === null) {
52+
throw new UnexpectedValueException('The resource must have a key specified.');
53+
}
4854

4955
$resource = [
5056
'data' => [
@@ -54,7 +60,10 @@ public function item(?string $resourceKey, array $data): array
5460
],
5561
];
5662

57-
unset($resource['data']['attributes']['id']);
63+
unset(
64+
$resource['data']['attributes']['id'],
65+
$resource['data']['attributes']['type']
66+
);
5867

5968
if (isset($resource['data']['attributes']['links'])) {
6069
$custom_links = $data['links'];

test/Serializer/JsonApiSerializerTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,35 @@ public function testSerializeCollectionWithExtraMeta()
8787
$this->assertSame($expectedJson, $scope->toJson());
8888
}
8989

90+
public function testSerializingItemResourceWithNestedType()
91+
{
92+
$bookData = [
93+
'id' => 1,
94+
'type' => 'books',
95+
'title' => 'Foo',
96+
'year' => '1991',
97+
];
98+
99+
$resource = new Item($bookData, new JsonApiBookTransformer());
100+
$scope = new Scope($this->manager, $resource);
101+
102+
$expected = [
103+
'data' => [
104+
'type' => 'books',
105+
'id' => '1',
106+
'attributes' => [
107+
'title' => 'Foo',
108+
'year' => 1991,
109+
],
110+
],
111+
];
112+
113+
$this->assertSame($expected, $scope->toArray());
114+
115+
$expectedJson = '{"data":{"type":"books","id":"1","attributes":{"title":"Foo","year":1991}}}';
116+
$this->assertSame($expectedJson, $scope->toJson());
117+
}
118+
90119
public function testSerializingItemResourceWithHasOneInclude()
91120
{
92121
$this->manager->parseIncludes('author');

0 commit comments

Comments
 (0)