File tree 3 files changed +41
-6
lines changed
3 files changed +41
-6
lines changed Original file line number Diff line number Diff line change @@ -200,13 +200,18 @@ Str::make('email')->writableOnCreate();
200
200
### Default Values
201
201
202
202
If you would like to provide a default value to be used when creating a new
203
- resource if there is no value provided in the request, you can pass a closure to
204
- the ` default ` method:
203
+ resource if there is no value provided in the request, you can pass a closure or
204
+ a literal value to the ` default ` method.
205
+
206
+ A closure will receive the current request context as an argument when called.
205
207
206
208
``` php
207
- use Tobyz\JsonApiServer\Field\DateTime ;
209
+ use Tobyz\JsonApiServer\Field;
208
210
209
- DateTime::make('joinedAt')->default(fn() => new \DateTime());
211
+ Field\Str::make('name')->default('Anonymous');
212
+ Field\DateTime::make('joinedAt')->default(
213
+ fn(Context $context) => new \DateTime(),
214
+ );
210
215
```
211
216
212
217
### Required
Original file line number Diff line number Diff line change @@ -51,8 +51,12 @@ public function required(bool $required = true): static
51
51
/**
52
52
* Set a default value for this field.
53
53
*/
54
- public function default (? Closure $ default ): static
54
+ public function default (mixed $ default ): static
55
55
{
56
+ if (!$ default instanceof Closure) {
57
+ $ default = fn () => $ default ;
58
+ }
59
+
56
60
$ this ->default = $ default ;
57
61
58
62
return $ this ;
Original file line number Diff line number Diff line change @@ -17,7 +17,7 @@ public function setUp(): void
17
17
$ this ->api = new JsonApi ();
18
18
}
19
19
20
- public function test_default_value_used_if_field_not_present ()
20
+ public function test_default_closure_value_used_if_field_not_present ()
21
21
{
22
22
$ this ->api ->resource (
23
23
new MockResource (
@@ -43,6 +43,32 @@ public function test_default_value_used_if_field_not_present()
43
43
);
44
44
}
45
45
46
+ public function test_default_literal_value_used_if_field_not_present ()
47
+ {
48
+ $ this ->api ->resource (
49
+ new MockResource (
50
+ 'users ' ,
51
+ endpoints: [Create::make ()],
52
+ fields: [
53
+ Attribute::make ('name ' )
54
+ ->writable ()
55
+ ->default ('default ' ),
56
+ ],
57
+ ),
58
+ );
59
+
60
+ $ response = $ this ->api ->handle (
61
+ $ this ->buildRequest ('POST ' , '/users ' )->withParsedBody ([
62
+ 'data ' => ['type ' => 'users ' ],
63
+ ]),
64
+ );
65
+
66
+ $ this ->assertJsonApiDocumentSubset (
67
+ ['data ' => ['attributes ' => ['name ' => 'default ' ]]],
68
+ $ response ->getBody (),
69
+ );
70
+ }
71
+
46
72
public function test_default_value_not_used_if_field_present ()
47
73
{
48
74
$ this ->api ->resource (
You can’t perform that action at this time.
0 commit comments