PermissionService.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * @Name
  4. * @Description
  5. * @Author 刘学玺
  6. * @Date 2024/8/18 22:44
  7. */
  8. namespace App\Http\Services\Backend\Server\System;
  9. use App\Enums\System\Role\DataScope;
  10. use App\Exceptions\ApiException;
  11. use App\Http\Services\Service;
  12. use App\Models\System\Menu;
  13. use App\Models\System\Role;
  14. use Ramsey\Uuid\Type\Integer;
  15. use Spatie\Permission\Guard;
  16. use Spatie\Permission\Models\Permission;
  17. use Symfony\Component\HttpFoundation\Response;
  18. class PermissionService extends Service
  19. {
  20. /**
  21. * @throws ApiException
  22. */
  23. public function assignPermission($params, $id): void
  24. {
  25. match ($params['type']) {
  26. 'role' => $this->assignRolePermission($params, $id),
  27. 'model' => $this->assignModelPermission($params, $id),
  28. default => self::error('PARAMS_TYPE_ERROR', Response::HTTP_UNPROCESSABLE_ENTITY)
  29. };
  30. }
  31. /**
  32. * @throws ApiException
  33. */
  34. public function assignRolePermission($params, $id): void
  35. {
  36. $params['guard_name'] = $params['guard_name'] ?? Guard::getDefaultName(static::class);
  37. // 获取角色
  38. $role = Role::findById($id, $params['guard_name']);
  39. !$role && self::error('ROLE_NOT_EXISTS', Response::HTTP_UNPROCESSABLE_ENTITY);
  40. // 获取多个权限
  41. $permissions = Permission::query()->whereIn('id', $params['permission'])->get();
  42. // 给角色添加多个权限
  43. $role->syncPermissions($permissions);
  44. // 记录操作日志上下文
  45. // LogRecordContext.putVariable("role", role);
  46. // return role.getId();
  47. }
  48. public function assignModelPermission($params, $id)
  49. {
  50. }
  51. public function getMenus($id, $class)
  52. {
  53. $classInstance = app($class);
  54. // 角色类型
  55. if ($class === Role::class) {
  56. $role = $classInstance::findById($id);
  57. return $role->getAllPermissions()->pluck('id');
  58. }
  59. return [];
  60. }
  61. }