-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAddParticipantToCompanyHandler.php
54 lines (47 loc) · 1.72 KB
/
AddParticipantToCompanyHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
namespace App\Actions\Users;
use App\Models\Company;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Mockery\Exception;
use Spatie\Permission\Models\Role;
class AddParticipantToCompanyHandler
{
/**
* Handles the adding of a user who registered as a participant to
* their company. The default role is company member, which is going to be assigned unless
* the user has a presentation or another role is passed
*
* @param User $user
* @param Company $company
* @param string $role
* @return void
*/
public function execute(User $user, Company $company, string $role = 'company member'): void
{
// Making sure, if something fails, everything will roll back
DB::transaction(function () use ($user, $company, $role) {
if ($user->company) {
throw new Exception('The user is already a member of a company. Are you sure this is the right user?');
}
$user->update([
'company_id' => $company->id
]);
if ($user->presenter_of) {
if (!$company->has_presentations_left) {
throw new Exception('The company has reached their presentation limit. Contact them to resolve this.');
}
$presentation = $user->presenter_of;
$presentation->update([
'company_id' => $company->id
]);
} else {
if (!Role::findByName($role, 'web')) {
throw new Exception('The role cannot be found');
}
$role = Role::findByName($role, 'web');
$user->assignRole($role);
}
});
}
}