1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace NovaFlexibleContent\Layouts\LayoutTraits; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Str; |
6
|
|
|
use Laravel\Nova\Fields\Field; |
7
|
|
|
use NovaFlexibleContent\Http\FlexibleAttribute; |
8
|
|
|
use NovaFlexibleContent\Http\ScopedRequest; |
9
|
|
|
|
10
|
|
|
trait HasFieldsRules |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Get validation rules for fields concerned by given request. |
14
|
|
|
*/ |
15
|
1 |
|
public function generateRules(ScopedRequest $request, string $key, ?string $type = null): array |
16
|
|
|
{ |
17
|
1 |
|
return $this->fieldsCollection()->map(fn ($field) => $this->getScopedFieldRules($field, $request, $key, $type)) |
|
|
|
|
18
|
1 |
|
->collapse() |
19
|
1 |
|
->all(); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Get validation rules for fields concerned by given request. |
24
|
|
|
*/ |
25
|
1 |
|
protected function getScopedFieldRules(Field $field, ScopedRequest $request, string $key, ?string $type = null): array |
26
|
|
|
{ |
27
|
1 |
|
$type = Str::ucfirst($type); |
28
|
1 |
|
$method = "get{$type}Rules"; |
29
|
|
|
|
30
|
1 |
|
$rules = []; |
31
|
1 |
|
if(method_exists($field, $method)) { |
32
|
1 |
|
$rules = call_user_func([$field, $method], $request); |
33
|
|
|
} |
34
|
|
|
|
35
|
1 |
|
return collect($rules) |
|
|
|
|
36
|
1 |
|
->mapWithKeys(function ($validatorRules, $attribute) use ($key, $field, $request) { |
37
|
1 |
|
$key = $request->isFileAttribute($attribute) |
38
|
|
|
? $request->getFileAttribute($attribute) |
39
|
1 |
|
: "{$key}.attributes.{$attribute}"; |
40
|
|
|
|
41
|
1 |
|
return [$key => $this->wrapScopedFieldRules($field, $validatorRules)]; |
42
|
1 |
|
}) |
43
|
1 |
|
->filter() |
44
|
1 |
|
->all(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Wrap the rules in an array containing field information for later use. |
49
|
|
|
*/ |
50
|
1 |
|
protected function wrapScopedFieldRules(Field $field, array $rules = []): array |
51
|
|
|
{ |
52
|
1 |
|
if (is_a($rules['attribute'] ?? null, FlexibleAttribute::class)) { |
53
|
|
|
return $rules; |
54
|
|
|
} |
55
|
|
|
|
56
|
1 |
|
return [ |
57
|
1 |
|
'attribute' => FlexibleAttribute::make($field->attribute, $this->inUseKey()), |
|
|
|
|
58
|
1 |
|
'rules' => $rules, |
59
|
1 |
|
]; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|