123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <?php
- /**
- * @Name
- * @Description
- * @Author 刘学玺
- * @Date 2024/8/18 22:44
- */
- namespace App\Http\Services\Backend\Server\System;
- use App\Enums\System\Role\DataScope;
- use App\Exceptions\ApiException;
- use App\Http\Services\Service;
- use App\Models\System\Menu;
- use App\Models\System\Role;
- use App\Models\System\User;
- use Illuminate\Support\Collection;
- use Ramsey\Uuid\Type\Integer;
- use Spatie\Permission\Guard;
- use Spatie\Permission\Models\Permission;
- use Symfony\Component\HttpFoundation\Response;
- class PermissionService extends Service
- {
- /**
- * @throws ApiException
- */
- public function assignPermission($params, $id): void
- {
- match ($params['type']) {
- 'role' => $this->assignRolePermission($params, $id),
- 'model' => $this->assignModelPermission($params, $id),
- default => self::error('PARAMS_TYPE_ERROR', Response::HTTP_UNPROCESSABLE_ENTITY)
- };
- }
- /**
- * @throws ApiException
- */
- public function assignRolePermission($params, $id): void
- {
- $params['guard_name'] = $params['guard_name'] ?? Guard::getDefaultName(static::class);
- // 获取角色
- $role = Role::findById($id);// query()->where('guard_name', $params['guard_name'])->find($id);
- !$role && self::error('ROLE_NOT_EXISTS', Response::HTTP_UNPROCESSABLE_ENTITY);
- // 清空菜单与角色的关联
- $menus = $role->menus;
- foreach ($menus as $menu) {
- $menu->removeRole($role->name);
- }
- // 添加菜单与角色的关联
- $syncMenus = Menu::query()->whereIn('id', $params['permission'])->get();
- $permissions = collect([]);
- foreach ($syncMenus as $menu) {
- // 添加菜单与角色的关联
- $menu->assignRole($role);
- // 获取菜单权限
- if (!$menu->permissions->isEmpty()) $permissions = $permissions->merge($menu->permissions);
- }
- // 给角色添加多个权限
- $role->syncPermissions($permissions);
- // 记录操作日志上下文
- // LogRecordContext.putVariable("role", role);
- // return role.getId();
- }
- public function assignModelPermission($params, $id)
- {
- }
- public function getPermissions(int $id, string $class)
- {
- $classInstance = app($class);
- // 角色类型
- if ($class === Role::class) {
- $role = $classInstance::findById($id);
- return $role->menus->pluck('id');
- }
- return [];
- }
- // 获取用户角色
- public function getUserRoles(int $id): Collection
- {
- return User::query()->find($id)->roles->pluck('id');
- }
- // 分配用户角色
- public function assignUserRole(array $data): void
- {
- $user = User::query()->find($data['userId']);
- $user->roles()->sync($data['roleIds']);
- }
- }
|