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.
This commit is contained in:
parent
919f6e1e42
commit
1facb19efb
@ -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();
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user