*/ 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> * @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]), ]; }); } }