Skip to content

Commit b34a5c2

Browse files
committed
Call user serializer before type serializer
Fixes #91
1 parent 54e85de commit b34a5c2

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

src/Schema/Field/Attribute.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,13 @@ public function serializeValue(mixed $value, Context $context): mixed
2222
return null;
2323
}
2424

25+
$value = parent::serializeValue($value, $context);
26+
2527
if ($this->type) {
2628
$value = $this->type->serialize($value);
2729
}
2830

29-
return parent::serializeValue($value, $context);
31+
return $value;
3032
}
3133

3234
public function deserializeValue(mixed $value, Context $context): mixed

tests/feature/FieldGetTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Tobyz\JsonApiServer\Endpoint\Show;
66
use Tobyz\JsonApiServer\JsonApi;
77
use Tobyz\JsonApiServer\Schema\Field\Attribute;
8+
use Tobyz\JsonApiServer\Schema\Type\Str;
89
use Tobyz\Tests\JsonApiServer\AbstractTestCase;
910
use Tobyz\Tests\JsonApiServer\MockResource;
1011

@@ -71,4 +72,32 @@ public function test_use_serializer_if_provided()
7172
$response->getBody(),
7273
);
7374
}
75+
76+
public function test_use_serializer_before_type()
77+
{
78+
$this->api->resource(
79+
new MockResource(
80+
'users',
81+
models: [(object) ['id' => '1', 'value' => 1]],
82+
endpoints: [Show::make()],
83+
fields: [
84+
Attribute::make('value')
85+
->type(Str::make())
86+
->serialize(function ($value) {
87+
if (is_string($value)) {
88+
$this->fail('value should not yet be a string');
89+
}
90+
return $value + 1;
91+
}),
92+
],
93+
),
94+
);
95+
96+
$response = $this->api->handle($this->buildRequest('GET', '/users/1'));
97+
98+
$this->assertJsonApiDocumentSubset(
99+
['data' => ['attributes' => ['value' => '2']]],
100+
$response->getBody(),
101+
);
102+
}
74103
}

tests/feature/NumberTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ public function test_validates_integer()
5656

5757
$this->expectException(UnprocessableEntityException::class);
5858

59-
$response = $this->api->handle(
59+
$this->api->handle(
6060
$this->buildRequest('POST', '/users')->withParsedBody([
6161
'data' => ['type' => 'users', 'attributes' => ['count' => 'hello']],
6262
]),

0 commit comments

Comments
 (0)