Skip to content

Commit 5b30abe

Browse files
Allow literal default values (#80)
Co-authored-by: bertramakers <bertramakers@users.noreply.github.com> Co-authored-by: Toby Zerner <toby.zerner@gmail.com>
1 parent 35193fa commit 5b30abe

File tree

3 files changed

+41
-6
lines changed

3 files changed

+41
-6
lines changed

docs/fields.md

+9-4
Original file line numberDiff line numberDiff line change
@@ -200,13 +200,18 @@ Str::make('email')->writableOnCreate();
200200
### Default Values
201201

202202
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.
205207

206208
```php
207-
use Tobyz\JsonApiServer\Field\DateTime;
209+
use Tobyz\JsonApiServer\Field;
208210

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+
);
210215
```
211216

212217
### Required

src/Schema/Concerns/SetsValue.php

+5-1
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,12 @@ public function required(bool $required = true): static
5151
/**
5252
* Set a default value for this field.
5353
*/
54-
public function default(?Closure $default): static
54+
public function default(mixed $default): static
5555
{
56+
if (!$default instanceof Closure) {
57+
$default = fn() => $default;
58+
}
59+
5660
$this->default = $default;
5761

5862
return $this;

tests/feature/FieldDefaultTest.php

+27-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public function setUp(): void
1717
$this->api = new JsonApi();
1818
}
1919

20-
public function test_default_value_used_if_field_not_present()
20+
public function test_default_closure_value_used_if_field_not_present()
2121
{
2222
$this->api->resource(
2323
new MockResource(
@@ -43,6 +43,32 @@ public function test_default_value_used_if_field_not_present()
4343
);
4444
}
4545

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+
4672
public function test_default_value_not_used_if_field_present()
4773
{
4874
$this->api->resource(

0 commit comments

Comments
 (0)