This commit is contained in:
86
app/Context/UserContext.php
Normal file
86
app/Context/UserContext.php
Normal file
@ -0,0 +1,86 @@
|
||||
<?php
|
||||
/**
|
||||
* Author: ykxiao
|
||||
* Date: 2025/6/3
|
||||
* Time: 下午10:38
|
||||
* Description:
|
||||
*
|
||||
* (c) ykxiao <yk_9001@hotmail.com>
|
||||
*
|
||||
* This source file is subject to the MIT license that is bundled
|
||||
* with this source code in the file LICENSE.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Context;
|
||||
|
||||
use App\Repository\Company\FirstCompanyRepository;
|
||||
use Exception;
|
||||
use Hyperf\Context\Context;
|
||||
use function Hyperf\Support\make;
|
||||
|
||||
class UserContext
|
||||
{
|
||||
private const string USER_KEY = 'user';
|
||||
|
||||
private const string TOKEN_KEY = 'token';
|
||||
|
||||
/**
|
||||
* 设置当前用户信息到 Context
|
||||
*
|
||||
* @param array|string|int $user 用户信息数组
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function setCurrentUser(array|string|int $user): void
|
||||
{
|
||||
$companyRepository = make(FirstCompanyRepository::class);
|
||||
if (!empty($companyInfo = $companyRepository->getCompanyByFullName($user['user']['full_name']))) {
|
||||
$user['company'] = $companyInfo;
|
||||
}
|
||||
|
||||
Context::set(self::USER_KEY, $user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Context 获取当前用户信息
|
||||
*
|
||||
* @return array|null 返回用户信息数组或 null 如果未找到
|
||||
*/
|
||||
public static function getCurrentUser(): ?array
|
||||
{
|
||||
return Context::get(self::USER_KEY);
|
||||
}
|
||||
|
||||
public static function hasCurrentUser(): bool
|
||||
{
|
||||
return Context::has(self::USER_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置当前用户令牌
|
||||
* @param string $token
|
||||
* @return void
|
||||
*/
|
||||
public static function setCurrentToken(string $token): void
|
||||
{
|
||||
Context::set(self::TOKEN_KEY, $token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Context 获取当前用户令牌
|
||||
* @return string|null
|
||||
*/
|
||||
public static function getCurrentToken(): ?string
|
||||
{
|
||||
return Context::get(self::TOKEN_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除当前用户信息
|
||||
*/
|
||||
public static function clearCurrentUser(): void
|
||||
{
|
||||
Context::set(self::USER_KEY, null);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user