ldc-tregalette/app/Http/Requests/Fo/Customers/CrmQuestionsAnswersRequest.php
2024-01-30 12:30:24 +01:00

109 lines
3.4 KiB
PHP

<?php
namespace App\Http\Requests\Fo\Customers;
use App\Models\Customer;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Arr;
use Illuminate\Validation\Rule;
use LDC\LDCCRM\Models\Question;
class CrmQuestionsAnswersRequest extends FormRequest
{
/**
* The crm questions that needs to be answered
*
* @var array<\LDC\LDCCRM\Models\Question>
*/
private array $questions = [];
/**
* Prepare the data for validation.
*
* @return void
*/
public function prepareForValidation(): void
{
if (!\auth('frontend')->check()) {
return;
}
/** @var \App\Models\Customer $customer */
$customer = auth('frontend')->user();
/** @var \LDC\LDCCRM\Models\Customer */
// @phpstan-ignore-next-line
$crmCustomer = $customer->apiData;
$this->questions = Customer::cacheCrm(
$customer->hashcode,
'questions',
fn () => Question::unansweredBy($crmCustomer)
);
}
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
if (!\auth('frontend')->check()) {
return false;
}
return (bool)\count($this->questions);
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string,\Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
* @throws \RuntimeException If a question type is unhandled.
*/
public function rules(): array
{
$rules = [];
foreach ($this->questions as $questionNumber => $question) {
switch ($question->type->value) {
case \LDC\LDCCRM\Enums\QuestionType::select()->value:
$rules["question.{$questionNumber}"] = ['required', Rule::in(
Arr::map($question->answers, fn ($answer) => $answer->id)
)];
break;
case \LDC\LDCCRM\Enums\QuestionType::radio()->value:
$rules["question.{$questionNumber}"] = ['required', Rule::in(
Arr::map($question->answers, fn ($answer) => $answer->id)
)];
break;
case \LDC\LDCCRM\Enums\QuestionType::checkbox()->value:
$rules["question.{$questionNumber}"] = 'required|array|min:1';
$rules["question.{$questionNumber}.*"] = ['required', Rule::in(
Arr::map($question->answers, fn ($answer) => $answer->id)
)];
break;
default:
throw new \RuntimeException("Unhandled question type {$question->type->value}");
};
} //end foreach
return $rules;
}
/**
* Get custom attributes for validator errors.
*
* @return array
*/
public function attributes(): array
{
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
return Arr::mapWithKeys($this->questions, function ($question, $index) {
return [
"question.{$index}" => trans('Question :number', ['number' => $index + 1]),
"question.{$index}.*" => trans('Question :number', ['number' => $index + 1]),
];
});
}
}