選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

AddCompanyEmployee.php 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Actions\FilamentCompanies;
  3. use App\Models\{Company, User};
  4. use Closure;
  5. use Illuminate\Auth\Access\AuthorizationException;
  6. use Illuminate\Contracts\Validation\Rule;
  7. use Illuminate\Support\Facades\{Gate, Validator};
  8. use Wallo\FilamentCompanies\Contracts\AddsCompanyEmployees;
  9. use Wallo\FilamentCompanies\Events\{AddingCompanyEmployee, CompanyEmployeeAdded};
  10. use Wallo\FilamentCompanies\FilamentCompanies;
  11. use Wallo\FilamentCompanies\Rules\Role;
  12. class AddCompanyEmployee implements AddsCompanyEmployees
  13. {
  14. /**
  15. * Add a new company employee to the given company.
  16. *
  17. * @throws AuthorizationException
  18. */
  19. public function add(User $user, Company $company, string $email, ?string $role = null): void
  20. {
  21. Gate::forUser($user)->authorize('addCompanyEmployee', $company);
  22. $this->validate($company, $email, $role);
  23. $newCompanyEmployee = FilamentCompanies::findUserByEmailOrFail($email);
  24. AddingCompanyEmployee::dispatch($company, $newCompanyEmployee);
  25. $company->users()->attach(
  26. $newCompanyEmployee,
  27. ['role' => $role]
  28. );
  29. CompanyEmployeeAdded::dispatch($company, $newCompanyEmployee);
  30. }
  31. /**
  32. * Validate the add employee operation.
  33. */
  34. protected function validate(Company $company, string $email, ?string $role): void
  35. {
  36. Validator::make([
  37. 'email' => $email,
  38. 'role' => $role,
  39. ], $this->rules(), [
  40. 'email.exists' => __('filament-companies::default.errors.email_not_found'),
  41. ])->after(
  42. $this->ensureUserIsNotAlreadyOnCompany($company, $email)
  43. )->validateWithBag('addCompanyEmployee');
  44. }
  45. /**
  46. * Get the validation rules for adding a company employee.
  47. *
  48. * @return array<string, Rule|array|string>
  49. */
  50. protected function rules(): array
  51. {
  52. return array_filter([
  53. 'email' => ['required', 'email', 'exists:users'],
  54. 'role' => FilamentCompanies::hasRoles()
  55. ? ['required', 'string', new Role]
  56. : null,
  57. ]);
  58. }
  59. /**
  60. * Ensure that the user is not already on the company.
  61. */
  62. protected function ensureUserIsNotAlreadyOnCompany(Company $company, string $email): Closure
  63. {
  64. return static function ($validator) use ($company, $email) {
  65. $validator->errors()->addIf(
  66. $company->hasUserWithEmail($email),
  67. 'email',
  68. __('filament-companies::default.errors.user_belongs_to_company')
  69. );
  70. };
  71. }
  72. }