Skip to content

Commit

Permalink
add default value resolver
Browse files Browse the repository at this point in the history
  • Loading branch information
iamgergo committed Feb 23, 2024
1 parent b14abbe commit 24886b2
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Fields/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ abstract class Field implements Arrayable, JsonSerializable
*/
protected ?Closure $formatResolver = null;

/**
* The default value resolver callback.
*/
protected ?Closure $defaultValueResolver = null;

/**
* The value resolver callback.
*/
Expand Down Expand Up @@ -342,6 +347,20 @@ public function resolveSearchQuery(Request $request, Builder $query, mixed $valu
: call_user_func_array($this->searchQueryResolver, [$request, $query, $value]);
}

/**
* Set the default value resolver.
*/
public function default(mixed $value): static
{
if (! $value instanceof Closure) {
$value = fn (): mixed => $value;
}

$this->defaultValueResolver = $value;

return $this;
}

/**
* Set the value resolver.
*/
Expand All @@ -363,6 +382,10 @@ public function resolveValue(Request $request, Model $model): mixed

$value = $this->getValue($model);

if (! is_null($this->defaultValueResolver)) {
$value = call_user_func_array($this->defaultValueResolver, [$request, $model]);
}

if (is_null($this->valueResolver)) {
return $value;
}
Expand Down

0 comments on commit 24886b2

Please sign in to comment.