AuthorityService.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Services;
  3. use App\Authority;
  4. use App\Role;
  5. use Exception;
  6. use Illuminate\Database\Eloquent\Builder;
  7. use Illuminate\Support\Facades\Auth;
  8. use Illuminate\Support\Facades\Cache;
  9. use App\Traits\ServiceAppAop;
  10. class AuthorityService
  11. {
  12. use ServiceAppAop;
  13. protected $modelClass=Authority::class;
  14. // /**
  15. // * @return Authority[]
  16. // */
  17. // function getAll(){
  18. // $authorities = Cache::get('authorities');
  19. // if(!$authorities){
  20. // $authorities = Authority::with('roles')->get();
  21. // Cache::put('authorities', $authorities, config('cache.expirations.authorities'));
  22. // }
  23. // return $authorities;
  24. // }
  25. //
  26. // /**
  27. // * @param Authority $authority
  28. // * @return Role[]
  29. // * @throws Exception
  30. // */
  31. // function getRoles(Authority $authority){
  32. // if(!$authority['id']??'') throw new Exception('User对象或id不能为空');
  33. // $roles = Cache::get('authorityGetRoles'.$authority['id']);
  34. // if(!$roles){
  35. // $roles = Authority::with('roles')->get();
  36. // Cache::put('authorities', $roles, config('cache.expirations.authorities'));
  37. // }
  38. // return $roles;
  39. // }
  40. public function getUserAuthority()
  41. {
  42. $key = "authorities:user_".Auth::id();
  43. if (!Cache::has($key)){
  44. if (array_search(Auth::user()["name"],config("users.superAdmin"))===false){
  45. Cache::tags("authorities:user")->forever($key,Authority::query()->whereHas("roles",function (Builder $query){
  46. $query->whereHas("users",function (Builder $query){
  47. $query->where("id",Auth::id());
  48. });
  49. })->get());
  50. }else Cache::tags("authorities:admin")->forever($key,$authorities = Authority::query()->get());
  51. }
  52. return Cache::get($key);
  53. }
  54. public function removeAdminAuth()
  55. {
  56. Cache::tags("authorities:admin")->flush();
  57. }
  58. public function removeAllAuth()
  59. {
  60. Cache::tags("authorities:admin")->flush();
  61. Cache::tags("authorities:user")->flush();
  62. }
  63. }