From 33e4d0f0133fd09e1a4cf1759f1a2ea01dd612b9 Mon Sep 17 00:00:00 2001 From: Oleksand-Moik Date: Tue, 25 Jan 2022 17:30:38 +0200 Subject: [PATCH] some updates --- composer.json | 2 +- src/Traits/HasRoles.php | 25 +++++++++++-------------- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/composer.json b/composer.json index 930289a..3855391 100644 --- a/composer.json +++ b/composer.json @@ -3,7 +3,7 @@ "description": "control access to models using groups and permissions", "license": "MIT", "type": "library", - "version": "2.1.1", + "version": "2.1.2", "authors": [ { "name": "Oleksandr-Moik", diff --git a/src/Traits/HasRoles.php b/src/Traits/HasRoles.php index 62e34a7..028b480 100644 --- a/src/Traits/HasRoles.php +++ b/src/Traits/HasRoles.php @@ -8,6 +8,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; +use Illuminate\Support\Collection; /** * For User model @@ -20,25 +21,24 @@ trait HasRoles public function roles(): BelongsToMany { return $this->belongsToMany(Role::class) - ->with('permissions', function (BelongsToMany $builder){ + ->with('permissions', function (BelongsToMany $builder) { return $builder->select('title'); }); } - public function getPermissionsAttribute(): \Illuminate\Support\Collection + public function getPermissionsAttribute(): Collection { - $permissions = collect(); - - $this->roles->each(function (Role $role) use (&$permissions) { - $permissions = $permissions->merge($role->permissions->pluck('title')); - }); - - return $permissions->unique(); + return $this->roles + ->reduce( + fn(Collection $carry, Role $role) => $carry->merge($role->permissions->pluck('title')), + collect() + ) + ->unique(); } public function hasPermissionKey(string $permission, ?string $module = null): bool { - if(isset($module)){ + if (isset($module)) { $permission = Permission::key($module, $permission); } @@ -48,10 +48,7 @@ public function hasPermissionKey(string $permission, ?string $module = null): bo public function hasAdminAccess(): bool { return $this->roles - ->filter(function (Role $role) { - return in_array($role->id, [Role::Admin, Role::SuperAdmin]) - || $role->admin_access; - }) + ->filter(fn (Role $role) => in_array($role->id, [Role::Admin, Role::SuperAdmin]) || $role->admin_access) ->count() > 0; }