CreateOrUpdateRequest.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Http\Requests\API\Approval;
  3. use App\Models\Enums\ApprovalObjectType;
  4. use App\Models\Enums\FileObjectType;
  5. use App\Models\Enums\ObjectApprovalStatus;
  6. use App\Models\File;
  7. use Illuminate\Foundation\Http\FormRequest;
  8. use Illuminate\Support\Facades\Auth;
  9. use Illuminate\Validation\Rules\Enum;
  10. class CreateOrUpdateRequest extends FormRequest
  11. {
  12. /**
  13. * Determine if the user is authorized to make this request.
  14. */
  15. public function authorize(): bool
  16. {
  17. return true;
  18. }
  19. /**
  20. * Get the validation rules that apply to the request.
  21. *
  22. * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
  23. */
  24. public function rules(): array
  25. {
  26. $rule = [];
  27. if ($this->method() == "POST") {
  28. $rule = [
  29. ...$rule,
  30. 'object_type' => [
  31. 'required',
  32. new Enum(ApprovalObjectType::class),
  33. ],
  34. 'object_id' => [
  35. 'required',
  36. function ($attribute, $value, $fail) {
  37. $exist = ApprovalObjectType::from($this->get("object_type"))
  38. ->modelBuilderAllowed($value)
  39. ->where("company_id", Auth::user()->company_id)
  40. ->where('id', $value)
  41. ->count();
  42. if (! $exist) {
  43. $fail('Resources without permission to access.');
  44. }
  45. }
  46. ],
  47. 'file_ids' => [
  48. 'array',
  49. function ($attribute, $value, $fail) {
  50. $count = File::query()
  51. ->where("company_id", Auth::user()->company_id)
  52. ->whereIn('id', $value)
  53. ->where("object_type", FileObjectType::CONTAINER)
  54. ->where("object_id", $this->get("object_id"))
  55. ->where("approval_status", ObjectApprovalStatus::WAIT)
  56. ->count();
  57. if ($count != count($value)) {
  58. $fail('Please select the file to be approved.');
  59. }
  60. }
  61. ]
  62. ];
  63. }
  64. return $rule;
  65. }
  66. }