CreateOrUpdateRequest.php 3.0 KB

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