generated from spatie/package-skeleton-laravel
-
-
Notifications
You must be signed in to change notification settings - Fork 217
/
Copy pathDataValidationMessagesAndAttributesResolver.php
88 lines (71 loc) · 2.73 KB
/
DataValidationMessagesAndAttributesResolver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
namespace Spatie\LaravelData\Resolvers;
use Illuminate\Support\Arr;
use Spatie\LaravelData\Support\DataConfig;
use Spatie\LaravelData\Support\Validation\ValidationPath;
class DataValidationMessagesAndAttributesResolver
{
public function __construct(
protected DataConfig $dataConfig,
) {
}
public function execute(
string $class,
array $fullPayload,
ValidationPath $path,
): array {
$dataClass = $this->dataConfig->getDataClass($class);
$messages = [];
$attributes = [];
foreach ($dataClass->properties as $dataProperty) {
$propertyPath = $path->property($dataProperty->inputMappedName ?? $dataProperty->name);
if (
$dataProperty->type->isDataObject === false
&& $dataProperty->type->isDataCollectable === false
&& $dataProperty->validate === false
) {
continue;
}
if (Arr::has($fullPayload, $propertyPath->get()) === false) {
continue;
}
if ($dataProperty->type->isDataObject) {
$nested = $this->execute(
$dataProperty->type->dataClass,
$fullPayload,
$propertyPath,
);
$messages = array_merge($messages, $nested['messages']);
$attributes = array_merge($attributes, $nested['attributes']);
continue;
}
if ($dataProperty->type->isDataCollectable) {
$collected = $this->execute(
$dataProperty->type->dataClass,
$fullPayload,
$propertyPath->property('*'),
);
$messages = array_merge($messages, $collected['messages']);
$attributes = array_merge($attributes, $collected['attributes']);
continue;
}
}
if (method_exists($class, 'messages')) {
$messages = collect(app()->call([$class, 'messages']))
->keyBy(
fn (mixed $messages, string $key) => ! str_contains($key, '.') && is_string($messages)
? $path->property("*.{$key}")->get()
: $path->property($key)->get()
)
->merge($messages)
->all();
}
if (method_exists($class, 'attributes')) {
$attributes = collect(app()->call([$class, 'attributes']))
->keyBy(fn (mixed $messages, string $key) => $path->property($key)->get())
->merge($attributes)
->all();
}
return ['messages' => $messages, 'attributes' => $attributes];
}
}