StoreStudentRequest.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace App\Http\Requests;
  3. use App\Models\User;
  4. use App\Services\StudentRegistrationDraftService;
  5. use Illuminate\Support\Facades\Auth;
  6. use Illuminate\Validation\Rule;
  7. use Illuminate\Validation\Validator;
  8. class StoreStudentRequest extends StudentRequest
  9. {
  10. private ?array $registrationDraft = null;
  11. protected function prepareForValidation(): void
  12. {
  13. $token = $this->input('registration_draft_token');
  14. $user = Auth::user();
  15. if (is_string($token) && $user instanceof User) {
  16. $this->registrationDraft = app(StudentRegistrationDraftService::class)
  17. ->findOwnedDraft($user, $token);
  18. if ($this->registrationDraft !== null) {
  19. // os dados validados do rascunho sao a fonte oficial. assim, o
  20. // payload final nao consegue sobrescreve-los sem nova validacao.
  21. $this->merge($this->registrationDraft['data']);
  22. }
  23. }
  24. parent::prepareForValidation();
  25. }
  26. public function rules(): array
  27. {
  28. $rules = parent::rules();
  29. $rules['registration_draft_token'] = [
  30. 'nullable',
  31. 'uuid',
  32. Rule::requiredIf(fn (): bool => $this->studentIsMinor()),
  33. ];
  34. $rules['responsible'][] = 'required_array_keys:name,birth_date,cpf,degree,email,phone,postal_code,street,neighborhood,city_id,state_id';
  35. return $rules;
  36. }
  37. public function after(): array
  38. {
  39. return [
  40. function (Validator $validator): void {
  41. if ($this->input('registration_draft_token') === null) {
  42. return;
  43. }
  44. if (
  45. !$validator->errors()->has('registration_draft_token')
  46. && $this->registrationDraft === null
  47. ) {
  48. $validator->errors()->add(
  49. 'registration_draft_token',
  50. __('validation.registration_draft_invalid'),
  51. );
  52. }
  53. },
  54. ];
  55. }
  56. }