| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <?php
- namespace App\Services;
- use App\Authority;
- use Illuminate\Database\Eloquent\Builder;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Cache;
- use App\Traits\ServiceAppAop;
- use Illuminate\Support\Facades\DB;
- class AuthorityService
- {
- use ServiceAppAop;
- protected $modelClass=Authority::class;
- public function getUserAuthority()
- {
- if (!Auth::user())return new Collection();
- $key = "authorities:user_".Auth::id();
- $isAdmin = array_search(Auth::user()["name"],config("users.superAdmin"))!==false;
- $tag = $isAdmin ? "authorities:admin" : "authorities:user";
- if (!Cache::tags($tag)->has($key)){
- if ($isAdmin) Cache::tags("authorities:admin")->forever($key,Authority::query()->get());
- else Cache::tags("authorities:user")->forever($key,Authority::query()->whereHas("roles",function (Builder $query){
- $query->whereHas("users",function (Builder $query){
- $query->where(DB::raw("users.id"),Auth::id());
- });
- })->get());
- }
- return Cache::tags($tag)->get($key);
- }
- public function removeAdminAuth()
- {
- Cache::tags("authorities:admin")->flush();
- }
- public function removeAllAuth()
- {
- Cache::tags("authorities:admin")->flush();
- Cache::tags("authorities:user")->flush();
- }
- /**
- * 格式化为树状结构
- *
- * @param Collection $authorities
- * @return array
- */
- public function format($authorities)
- {
- $authMap = [];
- foreach ($authorities as $authority){
- $item = $authority->toArray();
- $item["child"] = [];
- $authMap[$authority->id] = $item;
- }
- foreach ($authorities as $authority){
- if ($authority->parent_id){
- if (!isset($authMap[$authority->parent_id])){
- $authTem = $this->formatAuthority($authMap,$authMap[$authority->id]);
- if ($authTem)$authMap = $authTem;
- } else $authMap[$authority->parent_id]["child"][] = $authMap[$authority->id];
- unset($authMap[$authority->id]);
- }
- }
- return $authMap;
- }
- /**
- * 递归格式化权限组
- *
- * @param array $authMap
- * @param array $authorities
- *
- * @return array|bool
- */
- private function formatAuthority(array $authMap,array $authorities)
- {
- foreach ($authMap as $index=>$data){
- if ($data["id"]==$authorities["parent_id"]){
- $authMap[$index]["child"][] = $authorities;
- unset($authMap[$authorities["id"]]);
- return $authMap;
- }else{
- if ($authMap[$index]["child"]){
- $re = $this->formatAuthority($authMap[$index]["child"],$authorities);
- if ($re){
- $authMap[$index]["child"] = $re;
- return $authMap;
- }
- }
- }
- }
- return false;
- }
- }
|