Skip to content

Commit 9129e16

Browse files
authored
Merge pull request #2869 from josedaian/josedaian/dispatch-role-detached-on-sync-roles
Dispatch RoleDetached on syncRoles when events are enabled
2 parents 37739a4 + c3edf29 commit 9129e16

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

src/Traits/HasRoles.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,8 +225,15 @@ public function syncRoles(...$roles)
225225
{
226226
if ($this->getModel()->exists) {
227227
$this->collectRoles($roles);
228-
$this->roles()->detach();
229-
$this->setRelation('roles', collect());
228+
if (config('permission.events_enabled')) {
229+
$currentRoles = $this->roles()->get();
230+
if ($currentRoles->isNotEmpty()) {
231+
$this->removeRole($currentRoles);
232+
}
233+
} else {
234+
$this->roles()->detach();
235+
$this->setRelation('roles', collect());
236+
}
230237
}
231238

232239
return $this->assignRole($roles);

tests/HasRolesTest.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1042,4 +1042,43 @@ public function it_can_be_given_a_role_on_user_when_lazy_loading_is_restricted()
10421042
$this->fail('Lazy loading detected in the givePermissionTo method: '.$e->getMessage());
10431043
}
10441044
}
1045+
1046+
/** @test */
1047+
#[Test]
1048+
public function it_fires_detach_event_when_syncing_roles()
1049+
{
1050+
Event::fake([RoleDetached::class, RoleAttached::class]);
1051+
app('config')->set('permission.events_enabled', true);
1052+
1053+
$this->testUser->assignRole('testRole', 'testRole2');
1054+
1055+
app(Role::class)->create(['name' => 'testRole3']);
1056+
1057+
$this->testUser->syncRoles('testRole3');
1058+
1059+
$this->assertFalse($this->testUser->hasRole('testRole'));
1060+
$this->assertFalse($this->testUser->hasRole('testRole2'));
1061+
$this->assertTrue($this->testUser->hasRole('testRole3'));
1062+
1063+
$removedRoleIds = app(Role::class)::whereIn('name', ['testRole', 'testRole2'])
1064+
->pluck($this->testUserRole->getKeyName())
1065+
->toArray();
1066+
1067+
Event::assertDispatched(RoleDetached::class, function ($event) use ($removedRoleIds) {
1068+
return $event->model instanceof User
1069+
&& ! $event->model->hasRole('testRole')
1070+
&& ! $event->model->hasRole('testRole2')
1071+
&& $event->rolesOrIds === $removedRoleIds;
1072+
});
1073+
1074+
$attachedRoleIds = app(Role::class)::whereIn('name', ['testRole3'])
1075+
->pluck($this->testUserRole->getKeyName())
1076+
->toArray();
1077+
1078+
Event::assertDispatched(RoleAttached::class, function ($event) use ($attachedRoleIds) {
1079+
return $event->model instanceof User
1080+
&& $event->model->hasRole('testRole3')
1081+
&& $event->rolesOrIds === $attachedRoleIds;
1082+
});
1083+
}
10451084
}

0 commit comments

Comments
 (0)