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;
|
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\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
@ -20,7 +21,7 @@ final class Role extends Model
|
|||||||
*/
|
*/
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'name',
|
'name',
|
||||||
'slug'
|
'code'
|
||||||
];
|
];
|
||||||
|
|
||||||
public function scopeLatest(Builder $query): Builder
|
public function scopeLatest(Builder $query): Builder
|
||||||
@ -38,22 +39,17 @@ final class Role extends Model
|
|||||||
return $this->hasMany(RolePermission::class, 'role_id', 'id');
|
return $this->hasMany(RolePermission::class, 'role_id', 'id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function isRemove(): Attribute
|
||||||
/**
|
|
||||||
* Проверяем можем мы удалять эту группу или нет.
|
|
||||||
* Есть системные группы, которые нельзя удалять.
|
|
||||||
*/
|
|
||||||
public function isRemove(): bool
|
|
||||||
{
|
{
|
||||||
$dontRemove = SystemRoleEnum::toArray();
|
return Attribute::make(
|
||||||
return (array_search($this->slug, $dontRemove) === false);
|
get: fn ($dontRemove) => ( SystemRoleEnum::tryFrom($this->code) === null ),
|
||||||
|
)->shouldCache();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
protected function isAdmin(): Attribute
|
||||||
* Проверка эта группа самая главная или нет.
|
|
||||||
*/
|
|
||||||
public function isAdmin(): bool
|
|
||||||
{
|
{
|
||||||
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