Files
compras/app/Services/SubmissionAnswers.php
T
nala c6373365bf
tests / ci (push) Canceled after 0s
commit9
2026-10-30 20:02:30 +02:00

44 lines
1.7 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Support\Facades\Validator;
class SubmissionAnswers
{
/** Validate against the immutable definition chosen for the submission, never the latest company version.
* @param array<string,mixed> $definition
* @param array<string,mixed> $answers
* @return array<string,mixed>
*/
public function validate(array $definition, array $answers): array
{
$fields = $definition['fields'];
$keys = array_column($fields, 'key');
$rules = ['answers' => $keys === [] ? 'present|array|max:0' : 'present|array:'.implode(',', $keys)];
foreach ($fields as $field) {
$path = 'answers.'.$field['key'];
$presence = $field['required'] ? 'required' : 'nullable';
$rules[$path] = $presence.'|'.match ($field['type']) {
'location' => 'array:province,district,locality',
'number' => 'numeric',
'date' => 'date_format:Y-m-d',
'email' => 'email|max:254',
default => 'string|max:5000',
};
if ($field['type'] === 'location') {
foreach (['province', 'district', 'locality'] as $part) {
$rules[$path.'.'.$part] = 'required_with:'.$path.'|string|max:150';
}
}
}
return Validator::make(['answers' => $answers], $rules, [], [
'answers.availability_location' => 'local de disponibilidade',
'answers.availability_location.province' => 'província',
'answers.availability_location.district' => 'distrito',
'answers.availability_location.locality' => 'localidade',
])->validate()['answers'];
}
}