From 1facb19efb26cf26d1b695c26ecb38d65320567c Mon Sep 17 00:00:00 2001 From: Leonid Nikitin Date: Wed, 12 Jul 2023 23:42:29 +0600 Subject: [PATCH] Refactor Role.php for improved code clarity. The Role class in app/Models has been refactored to improve readability and maintainability. The 'slug' field was replaced with 'code' for consistency with the rest of the codebase. In addition, the 'isRemove' and 'isAdmin' methods were rewritten using new 'Attribute' Eloquent cast. This refactor enhances the code's clarity, promotes better comprehension, and clears redundant code comments. --- app/Models/Role.php | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/app/Models/Role.php b/app/Models/Role.php index ce81f3d..d5c8395 100644 --- a/app/Models/Role.php +++ b/app/Models/Role.php @@ -2,7 +2,8 @@ namespace App\Models; -use App\Models\Enums\SystemRoleEnum; +use App\Enums\SystemRole as SystemRoleEnum; +use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; @@ -20,7 +21,7 @@ final class Role extends Model */ protected $fillable = [ 'name', - 'slug' + 'code' ]; public function scopeLatest(Builder $query): Builder @@ -38,22 +39,17 @@ final class Role extends Model return $this->hasMany(RolePermission::class, 'role_id', 'id'); } - - /** - * Проверяем можем мы удалять эту группу или нет. - * Есть системные группы, которые нельзя удалять. - */ - public function isRemove(): bool + protected function isRemove(): Attribute { - $dontRemove = SystemRoleEnum::toArray(); - return (array_search($this->slug, $dontRemove) === false); + return Attribute::make( + get: fn ($dontRemove) => ( SystemRoleEnum::tryFrom($this->code) === null ), + )->shouldCache(); } - /** - * Проверка эта группа самая главная или нет. - */ - public function isAdmin(): bool + protected function isAdmin(): Attribute { - return ($this->slug === SystemRoleEnum::Admin->value); + return Attribute::make( + get: fn () => ( $this->code === SystemRoleEnum::Admin->value ), + )->shouldCache(); } }