Skip to content

Commit 9acc273

Browse files
authored
Merge pull request #2963 from chengkangzai/fix/sync-permissions-detached-event
Fire PermissionDetachedEvent when syncing permissions (symmetry with syncRoles)
2 parents 4a21798 + 623fbdf commit 9acc273

2 files changed

Lines changed: 40 additions & 2 deletions

File tree

src/Traits/HasPermissions.php

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -443,8 +443,17 @@ public function syncPermissions(...$permissions): static
443443
{
444444
if ($this->getModel()->exists) {
445445
$this->collectPermissions($permissions);
446-
$this->permissions()->detach();
447-
$this->setRelation('permissions', collect());
446+
447+
if (Config::eventsEnabled()) {
448+
$currentPermissions = $this->permissions()->get();
449+
450+
if ($currentPermissions->isNotEmpty()) {
451+
$this->revokePermissionTo($currentPermissions);
452+
}
453+
} else {
454+
$this->permissions()->detach();
455+
$this->setRelation('permissions', collect());
456+
}
448457
}
449458

450459
return $this->givePermissionTo($permissions);

tests/Traits/HasPermissionsTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -675,6 +675,35 @@
675675
});
676676
});
677677

678+
it('fires detach event when syncing permissions', function () {
679+
Event::fake([PermissionDetachedEvent::class, PermissionAttachedEvent::class]);
680+
app('config')->set('permission.events_enabled', true);
681+
682+
$this->testUser->givePermissionTo('edit-articles', 'edit-news');
683+
684+
$this->testUser->syncPermissions('edit-articles');
685+
686+
expect($this->testUser->hasPermissionTo('edit-articles'))->toBeTrue();
687+
expect($this->testUser->hasPermissionTo('edit-news'))->toBeFalse();
688+
689+
Event::assertDispatched(PermissionDetachedEvent::class, function ($event) {
690+
$names = collect($event->permissionsOrIds)->map(
691+
fn ($permission) => is_object($permission)
692+
? $permission->name
693+
: app(Permission::class)::findById($permission)->name
694+
);
695+
696+
return $event->model instanceof User
697+
&& ! $event->model->hasPermissionTo('edit-news')
698+
&& $names->contains('edit-news');
699+
});
700+
701+
Event::assertDispatched(PermissionAttachedEvent::class, function ($event) {
702+
return $event->model instanceof User
703+
&& $event->model->hasPermissionTo('edit-articles');
704+
});
705+
});
706+
678707
it('can be given a permission on role when lazy loading is restricted', function () {
679708
expect(Model::preventsLazyLoading())->toBeTrue();
680709

0 commit comments

Comments
 (0)