Skip to content

Commit 967787b

Browse files
committed
Modified required to be a closure to allow for logic behind the required field
1 parent 5645a85 commit 967787b

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

src/Endpoint/Concerns/SavesData.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ private function assertDataValid(Context $context, array $data, bool $validateAl
176176
foreach ($context->fields($context->resource) as $field) {
177177
$empty = !has_value($data, $field);
178178

179-
if ($empty && (!$field->required || !$validateAll)) {
179+
if ($empty && (!$field->isRequired($context) || !$validateAll)) {
180180
continue;
181181
}
182182

@@ -187,7 +187,7 @@ private function assertDataValid(Context $context, array $data, bool $validateAl
187187
];
188188
};
189189

190-
if ($empty && $field->required) {
190+
if ($empty && $field->isRequired($context)) {
191191
$fail('field is required');
192192
} else {
193193
$field->validateValue(get_value($data, $field), $fail, $context->withField($field));

src/Schema/Concerns/SetsValue.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ trait SetsValue
1111
{
1212
public ?Closure $writable = null;
1313
public ?Closure $writableOnCreate = null;
14-
public bool $required = false;
14+
public ?Closure $required = null;
1515
public ?Closure $default = null;
1616
public ?Closure $deserializer = null;
1717
public ?Closure $setter = null;
@@ -41,9 +41,9 @@ public function writableOnCreate(?Closure $condition = null): static
4141
/**
4242
* Mark this field as required.
4343
*/
44-
public function required(bool $required = true): static
44+
public function required(?Closure $condition = null): static
4545
{
46-
$this->required = $required;
46+
$this->required = $condition ?: fn() => true;
4747

4848
return $this;
4949
}
@@ -121,6 +121,14 @@ public function isWritableOnCreate(Context $context): bool
121121
($this->writableOnCreate && ($this->writableOnCreate)($context->model, $context));
122122
}
123123

124+
/**
125+
* Check if this field is required.
126+
*/
127+
public function isRequired(): bool
128+
{
129+
return $this->required && ($this->required)();
130+
}
131+
124132
/**
125133
* Deserialize a JSON value to an internal representation.
126134
*/

0 commit comments

Comments
 (0)