| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 | <?phpnamespace Modules\User\Http\Controllers;use Illuminate\Support\Collection;use Illuminate\Support\Facades\DB;use Modules\Common\Errors\Errors;use Modules\Common\Exceptions\CommonBusinessException;use Modules\User\Models\User;trait UserTrait{    // 当前登录用户    protected $currentUser;    /**     * 获取当前登录用户     * @return User     */    protected function getCurrentUser(): User {        if(!$this->currentUser) {            $this->currentUser = $this->getLoginUser();        }        return $this->currentUser;    }    /**     * 当前用户的所有的角色标识的结合     * @return Collection     */    protected function listUserRoles():Collection {        return $this->getCurrentUser()->roles->pluck('identify');    }    /**     * 当前用户是否是cp角色     * @return bool     */    public function userIsCp():bool {        return $this->listUserRoles()->contains('cp');    }    /**     * 如果当前用户是cp角色,返回cp_name,否则返回null     * @return string     */    public function getUserCpName():string|null {        if($this->userIsCp()) {            return DB::table('user_belong_to_cp')                ->where([                    'is_enabled' => 1,                    'user_id' => $this->getCurrentUser()->id,                ])->value('cp_name');        } else {            return null;        }    }    protected function getUserContext($operateUserId) {        $loginUser = $this->getLoginUser();        $loginUserRoles = $this->listUserRoles();        if($operateUserId) {            $operateUser = User::find($operateUserId);            $operateUserRoles = $operateUser->roles->pluck('identify');            if($loginUser->id != $operateUser->pid) {                CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);            }            if(!$operateUserRoles->contains('optimizer')) {                CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);            }        } else {            $operateUser = $loginUser;            $operateUserRoles = $loginUserRoles;        }        return compact('loginUser', 'loginUserRoles', 'operateUserRoles', 'operateUser');    }    /**     * 获取优化师用户uid     * @return int|null     */    public function getOptimizerUid() {        if($this->isOptimizer()) {            return $this->getCurrentUser()->id;        }        return null;    }    /**     * 是否是优化师     * @return bool     */    public function isOptimizer() {        return $this->listUserRoles()->contains('optimizer');    }    /**     * 是否是公司管理员     * @return bool     */    public function isCompanyManager() {        return $this->listUserRoles()->contains('company');    }}
 |