| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <?php
- namespace App\Models;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Relations\BelongsToMany;
- use Illuminate\Database\Eloquent\Relations\HasMany;
- class Role extends Model
- {
- const ADMIN = 'admin';
- const MANAGER = 'manager';
- const BRIGADIER = 'brigadier';
- const WAREHOUSE_HEAD = 'warehouse_head';
- const ASSISTANT_HEAD = 'assistant_head';
- const VALID_ROLES = [
- self::ADMIN,
- self::MANAGER,
- self::BRIGADIER,
- self::WAREHOUSE_HEAD,
- self::ASSISTANT_HEAD,
- ];
- const NAMES = [
- self::ADMIN => 'Админ',
- self::MANAGER => 'Менеджер',
- self::BRIGADIER => 'Бригадир',
- self::WAREHOUSE_HEAD => 'Рук. Склада',
- self::ASSISTANT_HEAD => 'Помощник рук.',
- ];
- protected $fillable = [
- 'slug',
- 'name',
- 'description',
- 'is_system',
- 'is_active',
- 'sort',
- ];
- protected function casts(): array
- {
- return [
- 'is_system' => 'boolean',
- 'is_active' => 'boolean',
- ];
- }
- public function permissions(): BelongsToMany
- {
- return $this->belongsToMany(Permission::class, 'role_permissions')
- ->withPivot('effect')
- ->withTimestamps();
- }
- public function users(): HasMany
- {
- return $this->hasMany(User::class);
- }
- public function hasPermission(string $permission): bool
- {
- return app(\App\Services\Access\AccessService::class)->roleHasPermission($this, $permission);
- }
- public function givePermission(string $permission, string $effect = 'allow'): void
- {
- $permissionModel = Permission::query()->where('slug', $permission)->firstOrFail();
- $this->permissions()->syncWithoutDetaching([
- $permissionModel->id => ['effect' => $effect],
- ]);
- app(\App\Services\Access\AccessService::class)->bumpCacheVersion();
- }
- public function syncPermissions(array $permissions): void
- {
- $sync = [];
- foreach ($permissions as $permission => $effect) {
- if (is_int($permission)) {
- $permission = $effect;
- $effect = 'allow';
- }
- $permissionModel = Permission::query()->where('slug', $permission)->first();
- if ($permissionModel) {
- $sync[$permissionModel->id] = ['effect' => $effect];
- }
- }
- $this->permissions()->sync($sync);
- app(\App\Services\Access\AccessService::class)->bumpCacheVersion();
- }
- public static function effectiveRoles(string $role): array
- {
- return match ($role) {
- self::ASSISTANT_HEAD => [self::ASSISTANT_HEAD, self::ADMIN, self::MANAGER],
- default => [$role],
- };
- }
- }
|